简体   繁体   English

来自 JSON 中 ajax 调用返回值的 Javascript 访问元素

[英]Javascript access element from return value of ajax call in JSON

So I make an ajax call that does return successfully but the problem is that I cannot access individual elements of the array it returns, meaning I can't console log it.所以我做了一个确实成功返回的ajax调用,但问题是我无法访问它返回的数组的各个元素,这意味着我无法控制台记录它。 It returns either error or undefined.它返回错误或未定义。 Error would be like track is not defined but when you look at the example ajax return, track is there.错误就像没有定义 track 一样,但是当您查看示例 ajax return 时, track 就在那里。 Here is the code这是代码

$.ajax({
            url: 'https://api.spotify.com/v1/playlists/'+playlist+'/tracks?fields=items(track.id)',
            headers: {
              'Authorization': 'Bearer ' + access_token
            },
            success: function(response,access_token) {
              Result(response,access_token);
            },
            dataType:"json"
        });

function Result(response,access_token){
      console.log(response[0].track.id);
      console.log(response[0]);
      console.log(response.track);
    }

The ajax call returns an array that looks like this for example.例如,ajax 调用返回一个看起来像这样的数组。 Inspecting an individual element.检查单个元素。

items: Array(80)
 -0:
  -track:
   -id: "Random String"

I read up on JSON methods and how it handles arrays and when I console logged response[0].track.id I believe I should see the id string.我阅读了 JSON 方法以及它如何处理数组,当我控制台记录 response[0].track.id 时,我相信我应该看到 id 字符串。 I also tried different console logs as well but have omitted because they all have the same kind of errors.我也尝试了不同的控制台日志,但都省略了,因为它们都有相同类型的错误。 I am trying to do this cause at one point I might put these ids in their own array and will need to add each individual element one at a time for further use.我正在尝试这样做,因为我可能会将这些 id 放在它们自己的数组中,并且需要一次添加每个单独的元素以供进一步使用。 Thank you for any assistance and let me know if you need more details.感谢您的任何帮助,如果您需要更多详细信息,请告诉我。

从检查的值...看起来你应该检查response.items[0].track.id代替...

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

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