2013-10-05 45 views
0

我有循環通過多個異步AJAX調用。該調用將循環迭代作爲索引。調用完成後,根據索引將數據存儲在數組中。AJAX異步返回錯誤索引

但是,成功函數中返回的索引與饋送給初始AJAX調用的索引不同。呼叫是否有一個很好的方式可以在呼叫初次饋送成功時返回相同的索引?

var ptype = 'fp'; 
    var pnum = 2; 
    var data = new Array(); 

    for(var i = 1; i <= 5; i++){ 
     call_general_forecast(ptype,i,pnum); 
    } 

function call_general_forecast(ptype, i1, pnum1){ 
     index = pnum1*5 + i1; 
     $.ajax({ 
      url: '', 
      data : { stock_name : stock_name, pattern: ptype, specificity : i1}, 
      type : 'get', //or 'post', but in your situation get is more appropriate, 
      dataType : 'json', 
      success : function(r) { 
       data[index] = r; 
       alert(index); 
      }, 
      async: true 

     });   
} 
+0

如果您必須並行運行多個AJAX調用,則可以將索引傳遞到您的服務器並將其作爲結果的一部分返回。 –

回答

1

您正在使用index作爲全局變量。使用關鍵字var將其聲明爲局部變量,閉包將爲您完成剩下的工作。所有成功函數都會有正確的索引(與請求發出時的值相同)。

function call_general_forecast(ptype, i1, pnum1){ 
    var index = pnum1*5 + i1; 
    $.ajax({ 
     url: '', 
     data : { stock_name : stock_name, pattern: ptype, specificity : i1}, 
     type : 'get', //or 'post', but in your situation get is more appropriate, 
     dataType : 'json', 
     success : function(r) { 
      data[index] = r; 
      alert(index); 
     }, 
     async: true 

    });   
} 
+0

你釘了它。謝謝!我會投票給你,但我需要15個代表點-_- –