2014-11-27 4 views
7

$.when은 동시에 쿼리 된 모든 여러 아약스 호출에 대한 지연 객체를 반환합니다.jQuery에서 지연된 객체를 사용하여 여러 아약스 호출에 대해 다른 성공 및 실패 상태 처리

모두 성공하면 .done()이 실행되고 URL 중 하나라도 실패하면 .fail()이 실행됩니다.

부분적인 성공 상태를 처리하는 방법은 무엇입니까? 즉, 5 개의 URL이 $.when으로 전달되면 3이 성공하면 성공 상태를 처리해야하며 2는 실패 상태를 처리해야하는 경우 실패합니다.

$.when($.getJSON(headerUrl), $.getJSON(tasksUrl), $.getJSON(testingTrackerUrl), $.getJSON(highlightsUrl))) 
    .then(function(headerData, tasksData,testingTrackerData,highlightsData) { 
     printData(headerData, tasksData,testingTrackerData,highlightsData); 
    }) 
    .fail(function(data, textStatus, jqXHR) { 
     console.error('Got error in '+jqXHR); 
}); 
+3

'$ .when', 그것은 그 해결 연기 마스터를 만들고 모든 기본 약속이 해결 때, 또는 근본적인 약속 중 하나가 실패하면 실패합니다. 다른 Ajax 호출에 대해 서로 다른 상태를 처리하려는 경우에는 inbetween가 없으므로 개별적으로 수행해야합니다. – adeneo

+0

@adeneo 예 중간 상태가 존재할 수 없다는 사실을 알고 있습니다. 하지만 부분적인 성공을 처리하고 여러 ajx 호출에 대한 상태를 처리하는 방법을 알고 싶습니다. jqXHR readystate를 사용하고 각 호출의 상태를 확인할 수 있습니까? 아니면 jQuery에 다른 방법이 있습니까? – user4300143

+0

각 Ajax 호출에 대해 적절한 콜백을 사용합니다. – adeneo

답변

5

시도

var request = function (url) { 
     return $.getJSON(url) 
} 
, requests = [ 
    headerUrl 
    , tasksUrl 
    , testingTrackerDataUrl 
    , highlightsDataUrl 
]; 
// return array of `resolved` , `rejected` jqxhr objects 
$.when(
    $.map(requests, function (_request, i) { 
     return request(_request) 
    }) 
) 
// do stuff with `resolved` , `rejected` jqxhr objects 
.always(function (arr) { 
    $.each(arr, function (key, value) { 
     // `success` 
     value.then(function (data, textStatus, jqxhr) { 
      console.log(data, textStatus, jqxhr); 
      printData(data) 
     } 
     // `error` 
     , function (jqxhr, textStatus, errorThrown) { 
      console.log(jqxhr, textStatus, errorThrown) 
     }) 
    }) 
}); 

jsfiddle http://jsfiddle.net/guest271314/91Lomwr3/

당신은 할 수없는
+0

코드 스 니펫이 크림처럼 작동 .. 감사합니다 :) – user4300143