Why is this jQuery.each not handling json data correctly?

Here is my ajax call:

$.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 is json it iterating over:

 [ {"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 element in the json array, it literally iterates over each character in the array one by one.

What am I doing wrong?

+4
source share
4 answers

You can change your $.each function $.each two ways:

 $.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 in your done function, not an object, then you need to run

 data = $.parseJSON(data) 

before the $.each

+9
source

Use this to indicate the current element inside .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); }); }); 
+4
source

Perhaps your server does not return the correct MIME type for JSON ('application / json'), and does JQuery interpret it as a string?

0
source

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 JSON parsing would be: jQuery.parseJSON( json ) as a temporary fix if the dataType type is being played ...

0
source

All Articles