Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 将动态变量附加到ajax回调函数_Jquery_Callback - Fatal编程技术网

Jquery 将动态变量附加到ajax回调函数

Jquery 将动态变量附加到ajax回调函数,jquery,callback,Jquery,Callback,我有一个发送ajax请求的循环。我想在ajax回调函数中包含循环索引: for (i=0;i<10;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

我有一个发送ajax请求的循环。我想在ajax回调函数中包含循环索引:

for (i=0;i<10;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);
        }
    })
}
for (i=0;i<10;i++) {
    (function(i) {
        $.ajax({ /* ... */ });
    })(i);
}

for(i=0;i您需要将其封装在一个闭包中。这应该可以做到:

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

for(i=0;i您必须围绕ajax请求创建一个闭包,以将请求回调函数的
i
值保留为本地值:

for (i=0;i<10;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);
        }
    })
}
for (i=0;i<10;i++) {
    (function(i) {
        $.ajax({ /* ... */ });
    })(i);
}

for(i=0;i您可以使用
data
返回索引参数以及其余数据

1: REST OF DATA HERE
只需从数据字符串中删除索引