0

我有这样的代码:

var links="";
function upload(file){
   var fd = new FormData();
   fd.append("image", file); // Append the file 
   // Create the XHR (Cross-Domain XHR FTW!!!)
   var xhr = new XMLHttpRequest();
   xhr.open("POST", "http://someapi.com");
   xhr.onload = function() {
      // Big win!
      // The URL of the image is:         
        links += "[IMG]"+JSON.parse(xhr.responseText).upload.links.original+"[/IMG]\n";                 
        //showResult(JSON.parse(xhr.responseText).upload.link);
   }
   // Ok, I don't handle the errors. An exercice for the reader.
   // And now, we send the formdata
   xhr.send(fd);
}
function catchFiles(files){
    nfiles = files.length;
    //var links="";
    for(var i=0;i<nfiles;i++){
        upload(files[i]);
    }                       
}
function showResult(links){     
    document.getElementById('div_result').innerText = links;                    
}

我想要的是如何等到 catchFiles 完成(上传完成的所有文件)之后,将调用 showResult。

有什么解决办法吗?

谢谢

4

2 回答 2

1

当 XHR 调用完成时,它会触发onreadystatechangewith readyState== 4。因此您需要为该事件分配一个函数,而不是onload

xhr.onreadystatechange = function(){
    if (xhr.readyState == 4){

        console.log(xhr.responseText);

    }
}
于 2012-11-27T17:24:40.080 回答
1

我找不到我提到的 jQuery 功能(也许是我想象的),所以我想出了另一个答案:

添加变量ajaxcounter并将其设置为您要发送的文件数,您可以在上传时计算它们,但这可能会带来在所有请求开始之前它达到 0 的风险,您最好对值进行硬编码,或者,如果它是动态设置的,则将所有准备好的 XHR 存储在一个数组中,并在您知道自己拥有所有内容时发送它们。

然后在您的上传功能中执行此操作:

xhr.onreadystatechange = function () {
    if(xhr.readystate == 4) {
        // Process the responseText
        ajaxDidFinish();
    }
}

并使其成为ajaxDidFinish功能:

function ajaxDidFinish() {
    ajaxCounter--;
    if(ajaxCounter == 0) {
        // All your requests should be ready now
    }
}

希望对你有帮助,我没有测试过。

于 2012-11-28T11:50:22.417 回答