简体   繁体   English

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

[英]How to access return data of jQuery.ajax()

I'm using the following code to make an AJAX call: 我正在使用以下代码进行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
      }
    }
  });

What I return to the AJAX request is: 我返回到AJAX请求的是:

{"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循环:

  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. tracklist是每个元素的关键,而不是其值。

Thus: 从而:

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

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

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