$(document).ready(function() {
var streamers = ["freecodecamp", "OgamingSC2", "cretetion", "ESL_SC2", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var status;
for (var i = 0; i < streamers.length; i++) {
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + streamers[i];
$.getJSON(url, function(data) {
if (data.stream === null) {
status = "Offline";
var url2 = "https://wind-bow.glitch.me/twitch-api/channels/" + streamers[i] + "";
$.getJSON(url2, function(data2) {
$("#container").append('<div class="row"><div class="col-sm-4"><img class="img-circle img-responsive" src="' + data2.logo + '"></div><div class="col-sm-4"><h2>' + data2.name + '</h2><p></div><div class="col-sm-4"><h2>' + status + '</h2></div></div><hr>');
});
} else {
console.log(data);
}
});
}
});for循环不适用于索引我的JSON URL。另外,有没有比使用两个getJSON请求更有效的方法呢?
发布于 2017-08-08 18:57:01
因为$.getJSON(url, function(data) { ...是异步调用,可以及时解决循环已经结束的问题。
发布于 2017-08-08 19:05:48
甚至在执行第一个回调之前,for-loop就一直运行到完成。这意味着第一次调用内部函数时,变量i等于streamers.length。
解决方案是在新变量中创建i的本地副本,并在回调中使用这些副本。let的使用确保了每个变量都是单独的副本,而不是重用的变量。
$(document).ready(function() {
var streamers = ["freecodecamp", "OgamingSC2", "cretetion", "ESL_SC2", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var status;
for(var i = 0; i < streamers.length; i++)
{
let j = i; // create local copy to store value of i.
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + streamers[j];
$.getJSON(url, function(data) {
if(data.stream === null) {
status = "Offline";
var url2 = "https://wind-bow.glitch.me/twitch-api/channels/" + streamers[j] + "";
$.getJSON(url2, function(data2) {
$("#container").append('<div class="row"><div class="col-sm-4"><img class="img-circle img-responsive" src="' + data2.logo + '"></div><div class="col-sm-4"><h2>' + data2.name + '</h2><p></div><div class="col-sm-4"><h2>' + status + '</h2></div></div><hr>');
});
}
else
{
console.log(data);
}
});
}
});发布于 2017-08-08 19:10:32
当执行第6行的ajax请求回调时,for循环已经结束,使用var删除的全局变量url的值是urlPrefix + arr[the last index],因此回调中的所有ajax都请求相同的url。
您可以阅读此doc about closure来了解为什么您的代码以这种方式运行。
https://stackoverflow.com/questions/45566396
复制相似问题