检测所有XMLHttpRequest调用已完成

时间:2014-11-21 08:25:57

标签: javascript jquery upload xmlhttprequest

我有将代码上传到服务器的Javascript代码。每次上传都是使用XMLHttpRequest对象完成的。

xhr = new XMLHttpRequest();

//...

xhr.open('POST', 'https://<bucket>.s3.amazonaws.com/', true);
xhr.send(fd);

并行上传工作正常。问题是我需要检测所有这些内容何时完成,因为我必须进行最终提交,但前提是所有上传都已完成。

我的第一次尝试是将所有xhr对象保存在一个数组中,但我不知道该怎么做: - (

var arrayxhr = [];

//...

//A loop {
    xhr = new XMLHttpRequest();
    arrayxhr.push(xhr);

    xhr.open('POST', 'https://<bucket>.s3.amazonaws.com/', true);
    xhr.send(fd);
//}

//And now?

我发现了这个jQuery函数https://api.jquery.com/ajaxcomplete/,但同样,我真的不知道如何使用它。

你能帮我吗?

TIA,

2 个答案:

答案 0 :(得分:2)

如果您可以使用jQuery,则可以使用jQuery AJAX Deferred接口/方法和$.when方法。 $.ajax/$.post/$.get和其他jQuery AJAX方法总是返回jQuery Deferred对象:

$.when($.get('someUrl'), $.get('anotherUrl')).then(function () {
    //all request complete
});

在原生javascript中,您可以使用原生Promise或任何承诺库:

关于Promises的好文章 - http://www.html5rocks.com/en/tutorials/es6/promises/

原住民PromiseXMLHttpRequest示例:

function doAjaxRequest(method, url, data){
  var promise = new Promise();
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);

  // Register the event handler
  xhr.onload = function(){
    if(xhr.status === 200){
      promise.resolve("Done");
    } else{
      promise.reject("Failed");
    }
  }; 

  data = data || {};

  xhr.send(data);

  return promise;
}

Promise.all(doAjaxRequest('post', 'someUrl'), doAjaxRequest('post', 'anotherUrl')).then(function (values) {
    //all request complete
});

答案 1 :(得分:0)

嗯,这不是我的问题的答案(检测到异步调用已完成),但这个答案对我有用。我在这里复制,以防它帮助其他人:

  

2:在客户端,创建一组要上载和上传的文件   一次一个,在&#34;完成&#34;上调用下一个。回调的   前。

https://stackoverflow.com/a/15557631/1893936

相关问题