处理来自多个AJAX JQuery的查询独立的数据 [英] Handling independant data from multiple AJAX JQuery queries
问题描述
我有一个数字,是从发送循环AJAX请求,并希望一些数据发送到回调函数取决于循环中的位置。
I have a number of AJAX requests that are sent from a for loop, and want to send some data to the call back functions depending on the position in the loop.
当我尝试将功能附加到每个请求,他们似乎都在最后一次通话中获取数据,例如,
When I try to attach a function to each request, they all seem to get the data from the last call, for instance,
for(var i=0; i < 4; i++){
data = ... //some unique data
req = $.post('/update/add', data, function(r_data, textStatus, jqxhr){
console.log(data);
}, "json")
}
将从I = 3项,而不是4个不同的项目给我的数据。我如何可以将这些数据传递给回调函数?
Would give me the data from the i = 3 entry instead of 4 different entries. How can I pass those data to the callback functions?
感谢你们......
Thank you guys...
推荐答案
现在的问题是,当一个闭包在我
变量,创建,它引用相同的变量,而不是创建一个新的我
变量。为了避免这种不良影响,你可以做到以下几点。
The problem is that when a closure is created over the i
variable, it references the same variable instead of creating a new i
variable. To avoid this undesirable effect, you can do the following.
for(var i=0; i < 4; i++){
data = ... //some unique data
req = $.post('/update/add', data, (function (i) {
//return a new callback function
return function (r_data, textStatus, jqxhr) {
//callback logic
//i will be the right index now
};
})(i), "json");
}
在上面的例子中,我们包装在被传递回路的我
值自动执行功能的回调函数。因为我
变量是在自动执行功能的范围定义,我们现在可以安全地返回一个新的回调函数,将创建一个封闭在我
的自动执行功能,而不是在循环使用的I
变量。
In the example above, we are wrapping our callback function in a self-executing function that is being passed the loop's i
value. Since the i
variable is defined in the scope of the self-executing function, we can now safely return a new callback function that will create a closure over the i
variable of the self-executing function instead of the i
variable used in the loop.
注:为了优化您的code,你能避免创建一个新的自动执行功能,每次
NOTE: To optimize your code, you could avoid creating a new self-executing function each time.
function createCallback(i) {
return function (r_data, textStatus, jqxhr) {
console.log(i);
};
}
/*
loop
post(..., createCallback(i));
*/
这篇关于处理来自多个AJAX JQuery的查询独立的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!