Handling independant data from multiple AJAX JQuer

2019-07-16 00:05发布

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")
}

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...

1条回答
倾城 Initia
2楼-- · 2019-07-16 01:07

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");
}

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.

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));
 */
查看更多
登录 后发表回答