开发者

Attaching dynamic variables to ajax callback function

开发者 https://www.devze.com 2023-03-26 07:06 出处:网络
I have a loop that sends ajax requests. I want to include the loop index in my ajax callback function:

I have a loop that sends ajax requests. I want to include the loop index in my ajax callback function:

for (i=0;i<10;i++) {
    $.ajax({
        data: "index="+i
        succ开发者_开发知识库ess: function (data) {
            //I want to be able to see the variable (i) here
            //since the request is async, it returns the last index on all
            $("#div"+i).append(data);
        }
    })
}


You'll need to wrap it up in a closure. This should do it:

for (i=0;i<10;i++) {
    (function(i) {
        $.ajax({
            data: "index="+i
            success: function (data) {
                //I want to be able to see the variable (i) here
                //since the request is async, it returns the last index on all
                $("#div"+i).append(data);
            }
        })
    })(i);
}


You have to create a closure around your ajax request to preserve the value of i as local for the request callback function:

for (i=0;i<10;i++) {
    (function(i) {
        $.ajax({ /* ... */ });
    })(i);
}


You could use data to return the index parameter as well as the rest of the data

1: REST OF DATA HERE

The just strip the index from the data string.

0

精彩评论

暂无评论...
验证码 换一张
取 消