2013-04-20 4 views
0

콜백의 배경에 대한 설명과 설명이있는 유사한 게시물에 대한 수많은 예제를 읽었지만 이해할 수 없습니다. 나는 특정한 시나리오를위한 해결책을 찾아 내고 '왜/어떻게'작동 하는지를 정말로 이해하지 못한다고해도 무대에 서게되었다. Ajax 호출을 반복해야하므로 이전 호출이 완료되기 전에 다음 호출을 막을 수있는 방법을 찾아야합니다. 콜백 또는 다른 방법을 사용하여 이러한 일이 발생하도록 제안 할 수 있습니까?아약스가 완료되기 전에 루핑을 막기위한 콜백

다음 코드는 작동하지만 ajax 호출을 1 회 1 회 실행하지 않으므로 메모리 오류 및 페이지 충돌이 발생합니다. 실행 기능은 매우 집중적 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가 실행되지 않도록하려면 어떻게 재정렬 할 수 있습니까?

미리 감사드립니다. 나는 비슷한 질문을 한 것을 알고 있습니다. 그래서 당신이 다른 설명으로 나를 안내하지 않도록 부탁드립니다. 기회는 제가 읽었지만 그 개념을 이해하지 못하는 것입니다.

건배!

추신. iterator()는 returnAjax() 함수의 각 인스턴스에 대해 새 매개 변수 값을 설정하므로 iterator() 함수는 returnAjax()가 완료 될 때만 실행해야한다는 것을 알고 있습니다.

+0

을 정의한다 :

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

그런 다음 당신은 이런 식으로 뭔가를 할 수 있습니까? –

답변

0

callback ajax 호출이 완료되면 호출됩니다. 새로운 요청 클래스는

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 
관련 문제