1

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

我知道使用 Jquery when() 的经典示例:

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

但当然,这是行不通的。想法?

4

2 回答 2

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
});
于 2012-07-01T04:35:11.827 回答
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 文件或文本文件,您可以将它们(data在 ajax 函数中)传递到loadTester那里并在那里累积(在像那些loadCounter和这样的私有 var 中loadEnds),并将累积的数组或对象传递给launch()

于 2012-07-01T07:07:58.813 回答