我有一个非常简单的问题,关于如何使用Ajax调用返回的JSON对象,以便稍后在我的程序中使用。我试图通过声明我自己的本地对象数组并将我想要的值放入其中来实现,但这是失败的,因为它显然无法找到我的数组。
以下是代码:
function getUsers() {
var users = [
{ name: "ESL_SC2", displayName:"", logo:"", url:"" },
{ name: "OgamingSC2", displayName: "", logo: "", url: "" },
{ name: "cretetion", displayName: "", logo: "", url: "" },
{ name: "freecodecamp", displayName: "", logo: "", url: "" },
{ name: "storbeck", displayName: "", logo: "", url: "" },
{ name: "habathcx", displayName: "", logo: "", url: "" },
{ name: "RobotCaleb", displayName: "", logo: "", url: "" },
{ name: "noobs2ninjas", displayName: "", logo: "", url: "" },
{ name: "MedryBW", displayName: "", logo: "", url: "" }
];
for (var i = 0; i < users.length; i++) {
var user = users[i].name;
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/channels/' + user,
headers: {
'Client-ID': 'xxxxx'
},
success: function (data) {
console.log(users[i].displayName + " is the display name");
users[i].displayName = data.display_name;
users[i].logo = data.logo;
users[i].url = data.url;
}
});
}
}
此错误立即失败:
getStreamData.js:22 Uncaught TypeError:无法读取属性&#39; displayName&#39;未定义的(...)
显然,这不是正确的方法。所以,我的问题是从Ajax调用存储结果的正确方法是什么,所以我可以在以后的代码中使用/操作它们?
感谢您的帮助!