Jquery从ajax调用的回调中推迟

时间:2012-07-01 04:32:07

标签: javascript jquery

我正在尝试编写一个过程,该过程在ajax函数的回调结果返回2个对象后执行某些操作。

我知道在():

时使用Jquery的经典示例
$.when($.get("http://localhost:3000/url1"), 
$.get("http://localhost:3000/url2").done(//do something));

但在我的情况下,我不想触发执行ajax函数的时候,我想要从执行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
});

但当然,这不起作用。想法?

2 个答案:

答案 0 :(得分: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
});

如果您不想一起处理请求,可以创建自己的延迟并使用:

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
});

答案 1 :(得分:0)

或者你可以自己做控制

     $(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();
      }
    });
  });

将您的文件添加到thingsToLoad数组中, 最后它将被迭代并将在成功后加载,它将是init loadTester

loadTester将检查thingsToLoad数组的长度,当加载的文件数与文件长度匹配且dom处于就绪状态时,它将launch()

如果你只是加载html文件或文本文件,你可以将那些({j}函数中的data)传递到loadTester并在那里积累(在私有变量中,如loadCounter }和loadEnds),并将累积的数组或对象传递给launch()