2013-04-20 58 views
0

我已經閱讀了類似帖子的無數例子,這些例子呼籲幫助,還有對回調背後理論的解釋,但我無法理解它。我已經走到了一個階段,我寧願爲我的特定場景找到一個解決方案,並繼續前進,即使我並不真正瞭解它爲什麼/如何運作。 我有一個ajax調用需要循環,並需要找到一種方法來防止在先前完成之前的下一個調用。你能否建議我如何使用回調或其他方法來實現這一點。在完成ajax之前阻止循環的回調

下面是代碼(它工作,但不運行ajax調用一對一,所以我得到內存錯誤和頁面崩潰)。運行該函數是相當密集,最多可能需要20秒(但是低達1秒)

function returnAjax(startLoc,startRow) 
{ 
     var url='index.php?option=com_productfinderrtw&format=raw&task=goThroughProcess'; 
     var data = 'startloc='+startLoc+'&starttour='+startRow; 
          var request = new Request({ 
          url: url, 
          method:'get', 
          data: data, 
          onSuccess: function(responseText){ 
    document.getElementById('fields-container').innerHTML= responseText; 
//I realise this is where on-success code cneeds to go- is this where the callback belongs? 
          } 
          }).send(); 

} 

function iterator (startLoc,startRow) { 
    if (startRow <20) 
     { 
     startRow++; 
     } 
     else 
     { 
     startRow = 1; 
     startLoc++; 
     } 
    return [startLoc, startRow]; 
} 


function runRAA() { 
    var startLoc = 0; 
    var startRow = 1; 

    while (startLoc < 47) 
    { 
    returnAjax(startLoc,startRow); 
    $counter = iterator(startLoc,startRow); 
     var newLoc = $counter[0]; 
     var newRow = $counter[1]; 

     startLoc = newLoc; 
     startRow = newRow; 
    } 
} 

runRAA()是,在按鈕按下運行的主要功能。我如何重新排列這個以確保在上一次完成之前returnAjax不會運行?

在此先感謝。我知道類似的問題已經被提出,所以我懇求你不要直接給我其他解釋 - 我已經閱讀過他們的機會,但是沒有把握這個概念。

乾杯!

PS。我知道只有當returnAjax()函數完成時,iterator()函數也需要運行,因爲iterator()爲每個returnAjax()函數實例設置了新的參數值。

+0

定義了新的要求類在哪裏? – 2013-04-20 19:02:13

回答

0

允許傳遞參數callback將在ajax調用完成時被調用。

function returnAjax(startLoc, startRow, callback) { 
    //... 
    onSuccess: function(responseText) { 
     document.getElementById('fields-container').innerHTML= responseText; 
     if (callback) { 
      callback.apply(this, arguments); //call the callback 
     } 
    } 
    //... 
} 

然後,你可以做這樣的事情:

function runRAA(startLoc, startRow) { 
     startLoc = startLoc || 0; 
     startRow = startRow || 1; 

     if (startLoc < 47) { 
      returnAjax(startLoc, startRow, function (responseText) { 
       var counter = iterator(startLoc, startRow); 

       //do something with the response 

       //perform the next ajax request 
       runRAA(counter[0], counter[1]); 

      })); 
     } 
    } 

    runRAA(); //start the process 
相關問題