检测所有 XMLHttpRequest 调用是否已完成

Detect all XMLHttpRequest calls are completed

本文关键字:是否 已完成 调用 XMLHttpRequest 检测      更新时间:2023-09-26

我有将文件上传到服务器的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,

如果可以使用jQuery则可以使用jQuery AJAX 延迟接口/方法和$.when方法。 $.ajax/$.post/$.get和其他 jQuery AJAX 方法始终返回 jQuery 延迟对象:

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

在原生 JavaScript 中,您可以使用原生Promise或任何 promise 库:

  • http://www.javascriptoo.com/rsvp-js
  • http://www.javascriptoo.com/Q(示例 https://gist.github.com/matthewp/3099268)

还有一篇关于承诺的好文章 - http://www.html5rocks.com/en/tutorials/es6/promises/。

本机Promise XMLHttpRequest示例:

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

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

2:在客户端,创建一堆要上传和上传的文件 一次一个,在 以前。

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