如何访问jQuery.ajax()的返回数据

时间:2011-05-22 15:59:35

标签: javascript jquery json

我正在使用以下代码进行AJAX调用:

  $.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
      }
    }
  });

我回到AJAX请求的是:

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

我想知道的是如何访问当前曲目列表的name属性。

3 个答案:

答案 0 :(得分:3)

你应该使用

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

而不是

console.log(tracklist.name);

答案 1 :(得分:2)

如果要迭代这些对象,最好返回一个数组:

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

然后,您可以使用类似于您尝试的for循环:

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

答案 2 :(得分:1)

在循环中:

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

tracklist是每个元素的关键,而不是它的价值。

因此:

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