jQuery ajax循环和迭代范围 [英] jQuery ajax loop and iteration scope
问题描述
我想知道为什么在 i 变量下面的代码中仍然显示"5" 而不是显示"1" ,然后显示"2" ,然后是"3" ,依此类推?必须是一个范围问题,但由于在全局和dom范围中更改了i变量的范围,但仍然遇到相同的问题,因此我并没有真正了解它. 当我在Ajax功能之外向 i 发出警报时,效果很好.
I'm wondering why in the code below the i variable still shows "5" instead of showing "1" then "2" then "3" and so on ? Must be a scope issue but I don't really get it as I changed the scope of i variable in global and dom scope and still getting the same problem. When I alert i outside the ajax function, it works well.
for (var i = 0; i < 5; i++) {
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i) // always 5
}
})
$('#outsideAjax').append(i); // is okay
}
这是小提琴
我选择了 @Tushar Gupta 解决方案,因为它最适合我的需求,但是又遇到了另一个问题,如果我设置以下选项,则迭代将无法进行: processData:false
I went for @Tushar Gupta solution as it best suits my needs but I get another issue, the iteration won't work if I set this option : processData: false
请参见小提琴
为什么这不起作用?
推荐答案
var i = 0;
function ajax_call() {
$.ajax({
url: '/echo/html/',
method: 'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i++);
if (i < 5) {
ajax_call();
}
}
});
$('#outsideAjax').append(i);
};
ajax_call();
这篇关于jQuery ajax循环和迭代范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!