在完成ajax之前阻止循环的回调

问题描述:

我已经阅读了类似帖子的无数例子,这些例子呼吁帮助,还有对回调背后理论的解释,但我无法理解它。我已经走到了一个阶段,我宁愿为我的特定场景找到一个解决方案,并继续前进,即使我并不真正了解它为什么/如何运作。 我有一个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

允许传递参数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