简体   繁体   English

为什么这个jQuery .each没有正确循环json数据?

[英]Why doesn't this jQuery .each loop through json data correctly?

Here's my ajax call: 这是我的ajax电话:

$.ajax({ 
    url: 'url-to-json',
    type: 'POST',
    dataType: 'json',
    cache: 'false',
    data: { lat: lat, lng: lng }
}).done(function(data) {
    $.each(data, function(a) {
        alert(data[a]);
    });
});

Here's the json it's iterating over: 这是它正在迭代的json:

[
{"Id":"4c75bd5666be6dcb9f70c10f","Name":"BXtra","EnglishName":null,"Lat":35.7515869140625,"Lng":139.33872985839844},

{"Id":"4c5160a1d2a7c9b655d51211","Name":"セブンイレブン 武蔵野台店","EnglishName":null,"Lat":35.750205993652344,"Lng":139.33448791503906},

...
]

But instead of actually giving me access to the properties of each item in the json array, it literally loops through each character in the array, one by one. 但是实际上不是让我访问json数组中每个项的属性,而是逐个遍历数组中的每个字符。

What am I doing wrong? 我究竟做错了什么?

You can modify your $.each function in two ways: 您可以通过两种方式修改$.each函数:

$.each(data, function(index,el) {
    // el = object in array
    // access attributes: el.Id, el.Name, etc
});

Or, 要么,

$.each(data, function() {
    // this = object in array
    // access attributes: this.Id, this.Name, etc
});

If data is a string within your done function and not an object, then you'll need to run 如果datadone函数中的字符串而不是对象,那么您将需要运行

data = $.parseJSON(data)

before your $.each loop $.each循环之前

Use this to refer to current element inside .each : this来引用里面的当前元素.each

$.ajax({ 
    url: 'url-to-json',
    type: 'POST',
    dataType: 'json',
    cache: 'false',
    data: { lat: lat, lng: lng }
}).done(function(data) {
    $.each(data, function() {
        alert(this.Id);
    });
});

也许你的服务器没有为JSON('application / json')返回正确的MIME类型,而JQuery正在将它解释为一个字符串?

Using success always works for me: 使用成功总是对我有用:

$.ajax({ 
  url: 'url-to-json',
  type: 'POST',
  dataType: 'json',
  cache: 'false',
  data: { lat: lat, lng: lng },
  success: function(data) {
    $.each(data, function() {
      alert(this.Id);
    });
  }
});

Forcing a parse of the JSON would be: jQuery.parseJSON( json ) as a temporary fix if the dataType is playing up... 强制解析JSON将是: jQuery.parseJSON( json )作为临时修复,如果dataType正在播放...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM