来自数组的多个ajax调用并在完成时处理回调 [英] Multiple ajax calls from array and handle callback when completed

查看:20
本文介绍了来自数组的多个ajax调用并在完成时处理回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前曾在 jQuery 中使用过 Promise - 但我无法将它应用于这种情况.我更喜欢使用 $.when() 和 $.done() 方法来实现这一点.

I have used promises in jQuery slightly before - but I am having trouble applying it to this scenario. I prefer to use the $.when() and $.done() methods to achieve this.

据我所知,我需要构建一个 $.Deferred 对象来记录请求,当这些请求完成时 - 触发回调.在我下面的代码中,回调在 ajax 请求之前触发 而不是之后 - 也许我只需要一些睡眠

From what I understand I need to build a $.Deferred object which logs the requests and when those requests are finished - fire the callback. In my code below the callback is firing before the ajax requests and not after - maybe I just need some sleep

我知道我的代码不完整,我一直在努力通过添加 for 循环来应用它.

I know my code is incomplete I have been struggling to apply it with the addition of the for loop.

http://jsfiddle.net/whiteb0x/MBZEu/

var list = ['obj1', 'obj2', 'obj3', 'obj4', 'obj5'];
var callback = function() {
  alert("done");
};
var requests = [];

var ajaxFunction = function(obj, successCallback, errorCallback) {
  for(i = 0; i < list.length; i++) {
    $.ajax({
      url: 'url',
      success: function() {
            requests.push(this);
      }
    });
  }
};
$.when($.ajax(), ajaxFunction).then(function(results){callback()});

推荐答案

$.when 的参数应该是 $.ajax 的返回值,它也不会不需要单独调用——这是没有意义的.你想要这样的东西:

The arguments to $.when should be the return value of $.ajax, which also doesn't need to be called separately -- that makes no sense. You want something like this:

for (i = 0; i < list.length; i++) {
   requests.push($.ajax(...));
}
$.when.apply(undefined, requests).then(...)

需要 .apply 的原因是因为 $.when 可以接受多个参数,但不能接受参数数组..apply 本质上扩展为:

The reason that .apply is needed is because $.when can take multiple arguments, but not an array of arguments. .apply expands essentially to:

$.when(requests[0], requests[1], ...)

这也假设请求可以按任何顺序完成.

This also assumes that the requests can be completed in any order.

http://jsfiddle.net/MBZEu/4/ -- 注意 'done' 记录到控制台在所有成功消息之后.

http://jsfiddle.net/MBZEu/4/ -- notice that 'done' is logged to the console after all of the success messages.

这篇关于来自数组的多个ajax调用并在完成时处理回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆