jQuery ajax循环和迭代范围
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.
我想知道为什么在下面的代码中,I变量仍然显示"5"而不是显示"1"然后"2"然后"3"等等?必须是一个范围问题,但我并没有真正理解,因为我在全局和dom范围中改变了I变量的范围,仍然得到了相同的问题。当我在ajax函数外部警告I时,它运行良好。
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
}
Here is the fiddle
这是小提琴
EDIT :
编辑:
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
我选择了@Tushar Gupta解决方案,因为它最适合我的需求,但我又遇到了另一个问题,如果我设置了这个选项,那么迭代将不起作用:processData: false。
See the fiddle
看到小提琴
Why is this not working ?
为什么它不能工作?
4 个解决方案
#1
0
fiddle Demo
小提琴演示
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();
更多相关文章
- 范围变量值的变化没有反映在我的字符串中
- 开心菜鸟系列----变量的解读(javascript入门篇)
- 如何使用变量创建数组?
- Angularjs:如何将范围变量传递给指令?
- 如何将razor变量传递给js
- 如何从Vue.js中的变量名加载组件?
- 将对象值传递给指令而不是任何其他数据变量
- 关于JavaScript变量声明及其初始化的问题
- 如何使用变量填充iframe源?