2011-06-10 5 views
3

루프를 입력하고 각 루프에 대해 비동기식 아약스 호출을 발행하는 javascript 함수가 있습니다. 그 시점에서 UI를 업데이트하려고하기 때문에 모든 아약스 호출이 반환되고 처리 된 시점을 알아야합니다.

루프는 다음과 같습니다

function sync_SyncLocalStorageToServer() { 
    if (helper_IsAppOnline()) { 
     $.log('sync_SyncLocalStorageToServer detects app is ONLINE'); 
     // Post each cached entry to the server - this is the main sync function 
     for (var i = 0, len = localStorage.length; i < len; i++) { 
      var lskey = localStorage.key(i); 
      if (lskey.substr(0, 8) === 'response') { 
       $.log('Sync found response with key=' + lskey); 
       var postdata = localStorage.getItem(lskey); // Get the form data 
       $.log('Calling server with ls response:' + postdata); 
       var localkey = lskey; 
       $.ajax({ 
        type: "POST", 
        dataType: 'json', 
        url: "/Profile/PostForm", 
        data: { jsonpost: postdata }, 
        success: function (data) { 
         if (data.rc == "success") { 
          localStorage.removeItem(data.localStorageKey); // Remove the relevant localStorage entry 
          $.log('ServerSuccess:' + data.message + ',removed localStorageKey=' + data.localStorageKey); 
         } else { 
          $.log('ServerUnhappy:' + data.message + ',did not remove localStorageKey=' + data.localStorageKey); 
         } 
        } 
      , error: function (data) { 
       $.log('ERR:' + data); 
      } 
       }); 
      } 
     } 
    } 
    else { 
     $.log('sync_SyncLocalStorageToServer detects app is OFFLINE'); 
    } 
} 

맨 마지막 비동기 아약스 호출이 결국 서버에서 반환 할 때 내 UI 새로 고침 함수를 호출하는 나를 위해 가장 쉬운 방법은 무엇입니까?

감사합니다.

답변

7

AJAX 요청을 실행 한 횟수를 계산 한 다음 완료된 콜백 호출 횟수를 계산하십시오. 콜백 완료 횟수와 아약스 호출 횟수가 같으면 완료되었음을 알 수 있습니다.

var total = arr.length; 
var count = 0; 
for(var i = 0; i < arr.length; i++){ 
    $.ajax({ 
     // other options 
     complete: function(){ 
      count++; 
      if(count == total){ 
       // all finished! 
      } 
     } 
    }); 
} 

요청 중 하나가 호출되지 않습니다 '성공'을하지 않을 경우 이후가의 '완전한'콜백이 아닌 '성공'를 사용 참고하지만 것이다 '완료'. 또한,이 예에서 세는 대신 '총'의 예상 금액을 먼저 선언했습니다. 이것은 보류중인 모든 Ajax 요청을 게시하기 전에 (기술적으로 가능한) 시나리오를 피할 수 있습니다. 따라서 모든 요청을 게시하고 일치하는 카운트를 가지기 만하면됩니다.

+0

그냥 함수의 맨 위에 var를 만들고 조정할 수 있습니까? 이런 식으로 가능한 범위 지정 또는 스레딩 문제가 있습니까? 매우 감사합니다. – Journeyman

+0

@Journeyman이 (가) 내 답변을 편집했습니다. – Matt

2

가장 쉬운 방법은 jQuery.ajaxStop 이벤트에 처리기를 연결하는 것입니다. 이보다 더 많은 후크가 필요한 경우 다른 global AJAX events에도 연결할 수 있습니다.