2011-08-05 38 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 

正好從數據字符串中除去索引。