2012-07-01 2 views
1

2 개체가 ajax 함수의 콜백의 결과로 반환 된 후 무언가를 수행하는 프로 시저를 작성하려고합니다. 아약스 기능의 실행에, 나는 경우에 원할 때 Jquery ajax 콜백 호출에서 지연된

$.when($.get("http://localhost:3000/url1"), 
$.get("http://localhost:3000/url2").done(//do something)); 

하지만 내 경우에는

, 내가 트리거하지 않습니다

나는() 할 때 jQuery를 사용하는 고전적인 예를 알고 ajax 함수를 실행하여 콜백에서 트리거합니다. 예 :

$.get("http://localhost:3000/url1", function(data){ 
    function(){ 
    //do something with the data, and return myobj1; 
    } 
}); 

$.get("http://localhost:3000/url2", function(data){ 
    function(){ 
    //do something with the data, and return myobj2; 
    } 
}); 

$.when(obj1, obj2).done(function(){ 
    //do something with these 2 objects 
}); 

물론 작동하지 않습니다. 아이디어?

답변

5

실제로 작동해야합니다. 그들은 모두 배열로 각각의 결과 인수를 반환 완료되면 jQuery.when() 여러 인수 및 화재를 취합니다

var req1 = $.get("http://localhost:3000/url1"); 
var req2 = $.get("http://localhost:3000/url2"); 

$.when(req1, req2).done(function(res1, res2) { 
    //do something with these 2 objects 
}); 

당신은 당신이 당신의 자신의 deferreds를 작성하고 그 사용할 수 있습니다 함께 요청을 처리하지 않으려는 경우 :

var deferred1 = $.Deferred(), 
    deferred2 = $.Deferred(); 

$.get("http://localhost:3000/url1", function(data){ 
    function(){ 
     //do something with the data, and return myobj1; 
     deferred1.resolve(myobj1); 
    } 
}); 

$.get("http://localhost:3000/url2", function(data){ 
    function(){ 
     //do something with the data, and return myobj2; 
     deferred2.resolve(myobj2); 
    } 
}); 

$.when(deferred1, deferred2).done(function(){ 
    //do something with these 2 objects 
}); 
+0

예, 게시 한 작품. 그러나 문제는 $ .get 함수가 돌아 왔을 때 언제 시작되는지, 위에서 언급 한 경우 $ .get 요청마다 콜백이 발생하며이 콜백이 처리되기를 기다리지 않는다는 것입니다. $ .get 함수가 끝나자. 그래서 언제 일찍 발포합니다. –

+0

@RyanOgle 어떤 이유로 든 응답을 처리 할 수 ​​없다면, 자신의 지연을 만들어이를 사용할 수 있습니다. 예제로 답변을 업데이트했습니다. – Trevor

+0

@ Trevor 여기에 뭔가 빠져 있어야합니다. 추가 된 예제에서 2 지연이 해결 될 때까지 트리거하지 않아야 할 때()입니까? 나는이 일을하지 않았다. 이 간단한 예제를 살펴보십시오. http://jsfiddle.net/ax4u4/ 지연된 오브젝트가 해결되지 않아도 when()이 트리거됩니다. –

0

또는 당신이 할 수는, thingsToLoad 배열로 파일을 추가 자신에게

 $(function(){$('body').addClass('doc-ready')}) 
    var thingsToLoad = ['blabla.js','blublu.js','weee.js']; 

    var launch = function(){ 

    // do whatever you want to do after loading is complete 
    // this will be invoked after dom ready. 
    // objectCollection will have everything you loaded. 

    // and you can wrap your js files in functions, and execute whenever you want. 

    } 

    var loadTester = (function() { 
     var loadCounter = 0, 
      loadEnds  = thingToLoad.length; // total number of items needs to be loaded 
     return function() { 
      loadCounter += 1; 
      if (loadCounter === loadEnds) { 
      if ($('body').hasClass('doc-ready')) { 
       launch(); 
      } else { 
       /* if body doesnt have ready class name, attach ready event and launch application */ 
       $(function() { 
       launch(); 
       }); 
      } 
      } 
     } 
     }()); 


$.each(thingsToLoad, function(i) { 
    $.ajax({ 
     url  : thingsToLoad[i], 
     mimeType : 'application/javascript', 
     dataType : 'script', 
     success : function(data) { 
     loadTester(); 
     } 
    }); 
    }); 

을 제어 0에서 끝까지 반복되고 성공 후로드됩니다. loadTester입니다.

loadTesterthingsToLoad 배열의 길이를 검사합니다.로드 된 파일 수와 파일 길이가 일치하고 준비 상태 인 dom은 launch()입니다.

그냥 HTML 파일 또는 텍스트 파일을로드하는 경우, 당신은 loadTester로 (아약스 기능에 data)들을 통과 할 수 있으며 (그 loadCounterloadEnds 같은 개인 VAR 이내)이 축적하고, 축적 된 배열 또는 개체를 전달 ~ launch()

관련 문제