问题
当使用AJAX查询远程API时,根据请求的异步性质,它会在完成时返回。问题是当我必须使用不同的标准对相同的API进行迭代调用时,我不知道哪个响应会回来。
问题:是否可以从
传递变量示例代码:(简化)
n=5;
for(i=0; i < n; i++) {
$.ajax({
url: someURL,
method: post,
// I don't want to have to use async: false, that's bad
// async: false,
data: JSON.stringify(someData),
beforeSend: function(){
console.log("Starting request #"+i)
},
error: function(err, code, text) {
alert("Something went wrong: \n\n" + code + ": " + text);
},
success: function(response) {
console.log("Response for request #"+i)
console.log(response)
}
})
}
最终的成功功能出现了问题:我应该看到的是:
Starting request #0
Starting request #1
Starting request #2
Starting request #3
Starting request #4
Response for request #2
[object]
Response for request #1
[object]
Response for request #4
[object]
Response for request #0
[object]
Response for request #3
[object]
我实际看到的是:
Starting request #0
Starting request #1
Starting request #2
Starting request #3
Starting request #4
Response for request #4
[object]
Response for request #4
[object]
Response for request #4
[object]
Response for request #4
[object]
Response for request #4
[object]
这一点很重要,不是因为我关心我的日志是正确的,而是因为实际版本需要能够将响应与发送的内容进行协调。我不想在这方面保持同步,因为它会变得缓慢,烦人,并且可能会超时。
答案 0 :(得分:5)
正如评论中所提到的,这是closures in loops更常见错误的一个特例。由于i
的值将在success
运行的时间内发生变化,因此您需要存储它(通过在循环外调用辅助函数来生成ajax请求)或绑定{{1}成功功能。例如:
i
答案 1 :(得分:1)
使用函数发出AJAX请求,并将i
传递给该函数:
var n = 5;
for(i = 0; i < n; i++) {
makeRequest(i);
}
function makeRequest(i) {
$.ajax({
url: url,
method: 'POST',
data: JSON.stringify(someData),
beforeSend: function(){
console.log("Starting request #"+i)
},
error: function(err, code, text) {
console.log("Response for request #"+i)
...
},
success: function(response) {
console.log("Response for request #"+i)
...
}
});
}