【发布时间】:2018-02-02 16:32:07
【问题描述】:
我正在尝试从 api 获取数据,但我使用的 For 循环在嵌套的 GetJSON 调用中返回具有 null 和未定义值的对象,但是当我尝试 forEach 循环时它工作正常。 有什么想法吗?
var baseUrl = "https://wind-bow.gomix.me/twitch-api/";
var channels = ["ESL_SC2", "FreeCodeCamp", "Test_channel", "brunofin"];
//**First function with forEach. WORKS FINE**
function getDataForEach() {
channels.forEach(function(channel) {
$.getJSON(txtUrl('streams', channel), function(json) {
console.log(json);
$.getJSON(txtUrl('channels', channel), function(json2) {
console.log(json2);
});
});
});
}
//**Second function with a normal for loop. The 2nd JSON doesnt return the proper data**
function getDataForLoop() {
for (i=0;i<channels.length;i++){
$.getJSON(txtUrl('streams', channels[i]), function(json) {
console.log(json);
//THIS 2nd call doesnt returns undefined objects.
$.getJSON(txtUrl('channels', channels[i]), function(json2) {
console.log(json2);
});
});
});
}
function txtUrl(prop, chnl) {
return baseUrl + prop + '/' + chnl + '?callback=?';
}
$(document).ready(function() {
getData();
});
【问题讨论】:
-
您是否尝试在第二次调用中设置断点并检查
i的值? -
是的。现在我明白为什么它不起作用了。
标签: javascript jquery ajax foreach getjson