2011-08-05 37 views
1

我有一个发送ajax请求的循环。我想在我的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); 
     } 
    }) 
} 

回答

2

您需要将它封装在闭包中。这应做到:

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

你必须建立在你的Ajax请求封闭保存的i值作为本地的请求回调函数:

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

你可以使用data返回索引参数以及其余数据

1: REST OF DATA HERE 

正好从数据字符串中除去索引。