简体   繁体   中英

How to access return data of jQuery.ajax()

I'm using the following code to make an AJAX call:

  $.ajax({
    url: href,
    type: 'POST',
    data: {},
    dataType: "json",
    error: function(req, resulttype, exc)
    {
      // do error handling
    },
    success: function(data)
    {
      for (var tracklist in data) {
        console.log(tracklist.name); // undefined
        console.log(tracklist['name']); // undefined
      }
    }
  });

What I return to the AJAX request is:

{"5":{"id":5,"name":"2 tracks","count":2},"4":{"id":4,"name":"ddddd","count":1},"7":{"id":7,"name":"Final test","count":2}}

What I would like to know is how to access the name attribute of the current tracklist.

You should use

console.log(data[tracklist].name);

instead of

console.log(tracklist.name);

If you want to iterate over those objects, it would be better if you returned an array:

[{"id":5,"name":"2 tracks","count":2},{"id":4,"name":"ddddd","count":1},{"id":7,"name":"Final test","count":2}]

Then, you could use a for-loop similar to what you were trying:

  for (var tracklist in data) {
    console.log(data[tracklist].id);
    console.log(data[tracklist].name);
  }

In the loop:

for (var tracklist in data) {
  console.log(tracklist.name); // undefined
  console.log(tracklist['name']); // undefined
}

tracklist is the key of each element, not its value.

Thus:

for (var tracklist in data) {
  console.log(data[tracklist].name); // ... or ...
  console.log(data[tracklist]['name']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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