For循环在Ajax调用中重复返回相同的值 [英] For loop returns same value repeatedly in Ajax call
本文介绍了For循环在Ajax调用中重复返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用来循环循环的URL数组,并使用它们进行ajax调用。在ajax调用之外,
i
正确地更改了值,但是当我尝试从调用中访问它时,它始终返回 2
。它循环正确,但具有相同的值,而不是通过 0,1
等循环。
var i = 0;
for(i = 0; i <= 1; ++ i){
console.log(Call =+ i外的值);
$ .ajax({
url:urls [i],
dataType:'jsonp',
timeout:3000,
count:0,
成功:函数(数据){
console.log(调用内部的值=+ i);
shotInfo [i] = data;
},
error:function (){
}
})
}
已经尝试过使用而
循环,但是它的效果是一样的。
你只有一个变量 i
。当回调触发时,它的最终值为 2
。
Make 封闭。
I'm trying to use a for
loop to cycle through an array of URLs and use them for ajax calls. Outside of the ajax call, i
changes value correctly, but when I try and access it from inside the call it always returns 2
. It loops correctly but with the same value instead of cycling through 0, 1
etc.
var i = 0;
for(i = 0; i <= 1; ++i) {
console.log("Value outside of call = " + i);
$.ajax({
url : urls[i],
dataType : 'jsonp',
timeout : 3000,
count : 0,
success : function(data) {
console.log("Value inside of call = " + i);
shotInfo[i] = data;
},
error : function() {
}
})
}
I've tried using a while
loop too, but it has the same effect.
解决方案
You only have one variable i
. When the callbacks fire, it has its final value of 2
.
Make a closure.
这篇关于For循环在Ajax调用中重复返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文