我是javascript的相对新手,我正在尝试在for循环中进行多个ajax调用。它在每次循环时使用不同的url为ajax调用循环遍历数组的元素。问题是变量'test'的值总是等于“condition4”。我习惯了其他语言,其中'test'的值将是“condition1”,然后是“condition2”等,因为它通过for循环。这是我的代码的简化版本:
var myData = [];
var cnt = 0;
var link;
var myCounter = 0;
var myArray = ["condition1", "condition2", "condition3", "condition4"];
for (x = 0; x < myArray.length; x++) {
link = "https://test.com/" + myArray[x];
myCounter = x;
GetJSON(function (results) {
for (i = 0; i < results.data.length; i++) {
var id = results.data[i].identifier;
var test = myArray[myCounter];
myData[cnt] = { "id": id, "test": test };
cnt++;
}
});
}
function GetJSON(callback) {
$.ajax({
url: link,
type: 'GET',
dataType: 'json',
success: function (results) {
callback(results);
}
});
}
答案 0 :(得分:1)
执行循环时,它会附加myCounter
引用。然后,由于异步任务,当它完成并调用“myCounter”时,它已经达到了数字4.因此,当它调用“myCounter”时,它就是4.要隔离在范围内,您需要在每次迭代时创建一个新范围并隔离&#39; myCounter&#39;
for (x = 0; x < myArray.length; x++) {
link = "https://test.com/" + myArray[x];
myCounter = x;
//IIFE
(function() {
var ownCounter = myCounter; //Isolating counter
GetJSON(function (results) {
for (i = 0; i < results.data.length; i++) {
var id = results.data[i].identifier;
var test = myArray[ownCounter];
myData[cnt] = { "id": id, "test": test };
cnt++;
}
});
})();
}
&#13;
或者...
for (let x = 0; x < myArray.length; x++) {
link = "https://test.com/" + myArray[x];
myCounter = x;
GetJSON(function (results) {
for (i = 0; i < results.data.length; i++) {
var id = results.data[i].identifier;
var test = myArray[x];
myData[cnt] = { "id": id, "test": test };
cnt++;
}
});
}
&#13;
答案 1 :(得分:0)
我认为您可以通过向服务器发送和接收myCounter值来解决此问题
for (x = 0; x < myArray.length; x++) {
link = "https://test.com/" + myArray[x];
myCounter = x;
$.ajax({
url: link,
type: 'GET',
dataType: 'json',
data: { myCounter: myCounter}
success: function(results) {
for (i = 0; i < results.data.length; i++) {
var id = results.data[i].identifier;
var test = results.data[i].myCounter
myData[cnt] = {
"id": id,
"test": test
};
cnt++;
}
}
});
}
&#13;