UFO ET IT

동적으로 여러 지연된 jQuery Ajax 호출

ufoet 2023. 8. 21. 23:21
반응형

동적으로 여러 지연된 jQuery Ajax 호출

jQuery http://api.jquery.com/jQuery.when/, 의 지연 패턴을 사용하여 여러 jsonp ajax 통화를 시도하고 결과를 기다린 후 다음 단계로 이동합니다..done()" 지연된 개체에서 해결된 인수 매개 변수의 수를 설정할 수 있기 때문에 고정된 호출 수를 사용하여 이 작업을 수행할 수 있습니다.그러나 내 애플리케이션에서는 통화 수가 동적이고 항상 알 수 없기 때문에 작동하지 않습니다.

.done() 해결 함수에서 args 수를 설정할 수 있기 때문에 이 첫 번째 단순화된 예제가 작동합니다..when()에 두 개의 호출이 있기 때문에 두 개가 필요하다는 것을 알고 있습니다.

$.when( $.ajax( url1 ), $.ajax( url2 ) ).done(function( a1, a2 ) {  
    var data = a1[ 0 ] + a2[ 0 ]; 
});

이것이 필요하지만 작동할 수 없는 것입니다.

var urls = GetUrlList(); // returns array of urls to json service
var requests = []; // hold ajax request
for (i = 0; i < urls.length; i++) {
    requests.push($.ajax(url[i]));
}

$.when.apply($, requests).done(function ("what goes here?") {
    // Need to get the data returned from all ajax calls here
});

이것에 대해 도움을 주셔서 감사합니다!

함수에 전달된 모든 인수를 포함하는 특별한 객체 킹인 인수를 사용할 수 있습니다.

$.when.apply($, requests).done(function () {
    console.log(arguments); //it is an array like object which can be looped
    var total = 0;
    $.each(arguments, function (i, data) {
        console.log(data); //data is the value returned by each of the ajax requests

        total += data[0]; //if the result of the ajax request is a int value then
    });

    console.log(total)
});

언급URL : https://stackoverflow.com/questions/19614354/dynamic-multiple-deferred-jquery-ajax-calls

반응형