gpt4 book ai didi

javascript - Ajax 请求,格式化结果时,如果我添加超过 2 行代码,某些元素会失败

转载 作者:行者123 更新时间:2023-11-30 06:20:50 25 4
gpt4 key购买 nike

抱歉,这个问题的措辞非常奇怪,我不知道如何解释。基本上,我有一个用作搜索的文本输入。每当您输入一个字母或单词时,它都会向 Spotify API 发出请求并返回 5 个最佳匹配结果;代码如下。

$("#SongSearch").keyup(function(){
$.ajax({
url: "https://api.spotify.com/v1/search?q=" + encodeURI(document.getElementById("SongSearch").value) + "&type=track&market=US&limit=5&offset=0",
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(InfoGained) {
document.getElementById("result1").innerHTML = InfoGained.tracks.items[0].name + ", " + InfoGained.tracks.items[0].artists[0].name;
document.getElementById("result2").innerHTML = InfoGained.tracks.items[1].name + ", " + InfoGained.tracks.items[1].artists[1].name;
document.getElementById("result3").innerHTML = InfoGained.tracks.items[2].name + ", " + InfoGained.tracks.items[2].artists[2].name;
document.getElementById("result4").innerHTML = InfoGained.tracks.items[3].name + ", " + InfoGained.tracks.items[3].artists[3].name;
document.getElementById("result5").innerHTML = InfoGained.tracks.items[4].name + ", " + InfoGained.tracks.items[4].artists[4].name;
}
});
});

此代码正确调用 API 并获取结果。但是,在格式化时,如果我添加了两个以上的 document.getElementByID... 行,则只有两行有效。例如,这有效:

$("#SongSearch").keyup(function(){
$.ajax({
url: "https://api.spotify.com/v1/search?q=" + encodeURI(document.getElementById("SongSearch").value) + "&type=track&market=US&limit=5&offset=0",
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(InfoGained) {
document.getElementById("result1").innerHTML = InfoGained.tracks.items[0].name + ", " + InfoGained.tracks.items[0].artists[0].name;
document.getElementById("result2").innerHTML = InfoGained.tracks.items[1].name + ", " + InfoGained.tracks.items[1].artists[1].name;
}
});
});

但是多了两行document.getElementID...,比如第一段代码列出导致错误:“Uncaught TypeError: Cannot read property 'name' of undefined”。感谢您的帮助,因为我真的不知道是什么原因造成的。提前致谢,贾斯汀

最佳答案

我盯着它看了一两个小时后才意识到 InfoGained.tracks.items[4].artists[4].name;正在为第 5 首歌调用第 5 位艺术家。它应该是 InfoGained.tracks.items[4].artists[0].name;谢谢大家的帮助,尤其是 Frax!

关于javascript - Ajax 请求,格式化结果时,如果我添加超过 2 行代码,某些元素会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53240545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com