1

我的网页中有 2 个部分需要单独的 AJAX 调用,然后是数据模板,然后再将内容注入 DOM。现在我正在寻找最好的方法,并且我已经阅读了很多关于 jQuery Deferreds 的文章,以至于我不完全确定最好的方法是什么。下面是我认为我会使用的代码,但我非常感谢一些输入。如果有人想对此添加一些建议,我也对缓存非常模糊。

JS

function ajaxCall1() {
    var dfd = $.Deferred();
    return $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/url1',
        data: { },
        success: function(data) {
            // Run templating code
        }
    });
    return dfd.promise();
}

function ajaxCall2() {
    var dfd = $.Deferred();
    return $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/url2',
        data: { },
        success: function(response) {
            // Run templating code
        }
    });
    return dfd.promise();
}

$.when( ajaxCall1(), ajaxCall2() )
   .then(function(){
      // Display DOM elements
   })
   .fail(function(){
      // Display error message
   });
4

1 回答 1

1

为了使用 Deferreds,你应该

1 - generate a new $.Deferred()
2 - return its .promise() from the function
3 - .resolve() the deferred in the callback of the Ajax request

有点像

function ajaxCall1() {
   var dfd = new $.Deferred();
   $.ajax({
      ...
      success: function(data) {
         dfd.resolve(data);
      }
   });
   return dfd.promise();
}

function ajaxCall2() {
   var dfd = new $.Deferred();
   $.ajax({
      ...
      success: function(data) {
         dfd.resolve(data);
      }
   });
   return dfd.promise();
}

$.when(ajaxCall1(), ajaxCall2()).then(function(data1, data2) {
   // data1 holds the result of the first ajax call, data2 that of the second call
});

编辑:由于 $.ajax() 已经返回一个延迟,你可以简单地做到这一点

function ajaxCall1() {
   return $.ajax({
      ...
   });
}

function ajaxCall2() {
   return $.ajax({
      ...
   });
}

$.when(ajaxCall1(), ajaxCall2()).done(function(data1, data2) {
   // data1 holds the result of the first ajax call, data2 that of the second call
});
于 2012-11-21T09:54:20.633 回答