Chaddeus
Chaddeus

Reputation: 13356

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

Here's 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's the json it's 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 item in the json array, it literally loops through each character in the array, one by one.

What am I doing wrong?

Upvotes: 4

Views: 6677

Answers (4)

Rick
Rick

Reputation: 997

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...

Upvotes: 0

jackwanders
jackwanders

Reputation: 16020

You can modify your $.each function in 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 within your done function and not an object, then you'll need to run

data = $.parseJSON(data)

before your $.each loop

Upvotes: 9

James Ellis-Jones
James Ellis-Jones

Reputation: 3092

Maybe your server is not returning the right MIME type for JSON ('application/json') and JQuery is interpreting it as just a string?

Upvotes: 0

Zbigniew
Zbigniew

Reputation: 27584

Use this to refer to 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);
    });
});

Upvotes: 4

Related Questions