Jquery 将动态变量附加到ajax回调函数
我有一个发送ajax请求的循环。我想在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
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
只需从数据字符串中删除索引