2014-11-21 85 views
0

我有Javascript代码将文件上传到服务器。每次上传都使用XMLHttpRequest对象完成。检测所有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

如果你可以使用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 
}); 
+0

,承诺的事情似乎就是我要找的。我现在正在检查... – 2014-11-21 08:42:37

+0

它现在不是跨浏览器,但是您可以使用其中一个丰富的库和polyfills – Pinal 2014-11-21 08:44:17

+0

还要添加一个本地Promise示例。 – Pinal 2014-11-21 08:49:33

0

好了,这是不完全的回答我的问题(检测到异步调用完成),但这个答案对我的作品。我复制到这里,以防万一它可以帮助别人:

2:在客户端,创建一堆文件上传和上传 一次一个,呼吁“完整”的回调下一个之前的 。

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