jQuery ajax 内循环问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2687679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery ajax inside a loop problem
提问by steamboy
This js loop script always get the last value of ui_item inside a jquery ajax funciton. How can a catch the correct value of each iteration?
这个js循环脚本总是在jquery ajax函数中获取ui_item的最后一个值。如何捕获每次迭代的正确值?
for (var i = 0; i <= split_files_cb_value_holder.length - 1; i++){
var split_values = split_files_cb_value_holder[i].split(':');
ui_item = split_files_cb_value_holder[i];
$.ajax({
type: "POST",
url: "ds/index.php/playlist/check_folder",
data: "component_type="+$('#component_type').val()+"&value="+split_values[1],
success: function(msg)
{
console.log(ui_item); //ALWAYS GETS THE LAST VALUE
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
});
}
Thanks!
谢谢!
回答by SLaks
The problem is that the anonymous callback method captures the ui_item
variable by reference. Since there is only one variable, it always gets whatever was assigned last to the variable.
问题在于匿名回调方法ui_item
通过引用捕获变量。由于只有一个变量,它总是获取最后分配给该变量的任何内容。
You need to wrap the contents of the for
loop in a function that takes i
as a parameter, then call the function in the loop. Each call to the wrapper function will create a separate variable, solving the problem.
您需要将for
循环的内容包装在一个i
作为参数的函数中,然后在循环中调用该函数。每次调用包装函数都会创建一个单独的变量,从而解决问题。
For example:
例如:
function doCheck(i) {
var split_values = split_files_cb_value_holder[i].split(':');
var ui_item = split_files_cb_value_holder[i];
$.ajax({
type: "POST",
url: "ds/index.php/playlist/check_folder",
data: "component_type="+$('#component_type').val()+"&value="+split_values[1],
success: function(msg)
{
console.log(ui_item); //Don't always get the last value
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
});
}
for (var i = 0; i < split_files_cb_value_holder.length; i++)
doCheck(i);
回答by Huseyin Zeki
Turn async off, it will fix the problem i guess. I mean add this: async:false
关闭异步,它会解决我猜的问题。我的意思是添加这个: async:false