jQuery ajax 内循环问题 [英] jQuery ajax inside a loop problem
问题描述
这个js循环脚本总是在jquery ajax函数中获取ui_item的最后一个值.如何捕获每次迭代的正确值?
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?
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");
}
});
}
谢谢!
推荐答案
问题是匿名回调方法通过引用捕获ui_item
变量.因为只有一个变量,所以它总是得到最后分配给变量的任何东西.
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.
您需要将for
循环的内容包裹在一个以i
为参数的函数中,然后在循环中调用该函数.每次调用包装函数都会创建一个单独的变量,从而解决问题.
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.
例如:
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);
这篇关于jQuery ajax 内循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!