Possible Duplicate:
Javascript infamous Loop problem?
我在尝试访问 $.post
内的变量时遇到问题功能。
变量的值a
函数内部始终相同:7。但在它之外,它会按照我的意愿增加。
为什么会发生这种情况?我怎样才能为 $.post
做一个循环功能?
for(var a=0; a<7; a++){
console.log(a); /* increasing value */
$.post("http://"+ document.domain + "/posts/user/xxxxx",
function(departments){
console.log(a); /*value of 7*/
});
}
谢谢。
最佳答案
要么为每个 for 迭代提供其自己的范围,要么使用 $.ajax
和 context
选项。
for(var a=0; a<7; a++){
(function(a){
console.log(a); /* increasing value */
$.post("http://"+ document.domain + "/posts/user/xxxxx",
function(departments){
console.log(a); /*value of 7*/
});
})(a);
}
与$.ajax
...
for(var a=0; a<7; a++){
console.log(a); /* increasing value */
$.ajax({
url: "http://"+ document.domain + "/posts/user/xxxxx",
type: "POST",
context: a,
success: function(departments){
console.log(this); /*value of 7*/
}
});
}
关于javascript - for 循环内的异步 $.post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13705879/