2014-06-19 2 views
4

공통된 이벤트에서 트리거되는 AJAX 호출 수가 가변적 인 페이지가 있습니다. AJAX 호출은 SQL 데이터베이스의 관련 필드를 업데이트하는 것입니다. 모든 통화가 완료되면 방금 변경된 내용을 반영하도록 페이지를 새로 고침하고 싶습니다. .when()에서 deffered 객체를 사용할 때 .when(). then()을 사용하여 함수를 트리거하는 방법은 무엇입니까?

나는 여기 jQuery when each is completed, trigger function

지금까지 내 코드입니다 .. 지금까지 얻을 여기에 답/다음과 같은 질문을 사용 : 내가 일어날 것으로 예상 된 것은 $('#content-wrapper').load('index.php');이다

var team_update = function(e) { 
    var $items = $('.sortable-items'); 
    var XHRs = []; 

    $items.each(function(){ 
     var team_id = $(this).attr("id"); 
     var data = { 
      tid: team_id, 
      users: $('#' + team_id).sortable('toArray') 
      }; 

     XHRs.push(
      $.ajax({ 
       type: "POST", 
       url: "update.php", 
       data: data, 
       complete: function(data){ 
       } 
      }) 
     ); 

    }); 

    $.when(XHRs).then(function(){ 
     console.log('Refreshing Screen'); 
     $('#content-wrapper').load('index.php'); 
    }); 

} 

모든 AJAX() 요청이 완료되면 발동 할 것입니다. 무슨 일이 일어나고 있는지, 모든 요청이 완료된 후에 반드시 콜백이 실행되고 있으므로 가끔 내 페이지 업데이트에 '오래된'데이터가 남아있는 경우 콜백이 실행된다는 것입니다.

아래 그래픽은 무시할 수있는 맨 위의 초기 페이지로드를 보여줍니다. 문제를 보여주는 다음 4 개의 항목입니다. DB를 업데이트하기위한 3 번 ajax 호출 인 3 번의 POST 요청과 마지막 페이지 새로 고침이 있습니다. 3 개의 아약스 호출이 모두 전송 된 후에 페이지 새로 고침이 실행되지만 마지막 아약스 호출이 완료되기 전에 완료 될 때까지 기다리지 않습니다. 결과적으로 이전 Ajac 호출이 데이터베이스 업데이트를 완료하기 전에 완료 될 때 이전 데이터를 가져옵니다.

Firebug timeline

내가 잘못 여기서 뭐하는 거지?

답변

5

나는 최근에 비슷한 것을 적용했다.

when()은 지연된 개체 또는 지연된 개체의 목록을 예상하지만 배열을 사용하려면 apply()을 사용해야합니다.

function SendAjax(data){ 
return $.ajax({Options as they are in your ajax call}); 
} 

를 다음에 밀어 :

이 작동하지 않는 경우 함수에서 Ajax 호출을 래핑해야 할 수도 있습니다,

$.when(XHRs) 

$.when.apply(null, XHRs) 

로 교체 XHR 등 :

내 코드에서이를 구현하는 방법을

다음가 필요한 경우, 당신은이 적응할 수 :

//We want to notify how many memberships have been made after they're all made. since they're async, we'll need to use promises 
//however, because we repeat the same ajax call with different parameters, we need to push them to an array and then apply() them. 
checkedBoxes.each(function() { 
    createArray.push(CreateMembershipsAjax(this)); 
}); 
//we did the work before we start creating them, so show some progress; 
add1ToProgress(); 
$.when.apply(null, createArray).done(function() { 
    //this function will only start once all ajax calls have been successfull. 
    divCreated.append(membershipCount + " memberships created:"); 
    MembershipsCreated = true; 
    window.close(); 
}); 

... 

CreateMembershipsAjax(element){ 
    //process element, create Data from it; 
    return $.ajax({option}); 
} 

그리고 네, 코멘트 내 코드에서 실제로 그냥이 페이지에 설명 추가하지.

+0

Spot on! 나는 apply를 사용하는 것과 관련된 또 다른 게시물을 보았지만 그것을 사용하는 방법에 대해서는 jQuery 문서에서 아무것도 발견하지 못했습니다. '$ .when.apply (null, XHRs)'이 치료를했습니다. 감사. – Boidy

+1

방금 ​​내 대답의 첫 번째 줄에 의도하지 않은 말장난을 발견했습니다. – Nzall

관련 문제