等到ajax完成

时间:2012-11-27 17:11:56

标签: javascript ajax

我有这样的代码:

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将被调用。

任何解决方案?

由于

2 个答案:

答案 0 :(得分:1)

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

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

        console.log(xhr.responseText);

    }
}

答案 1 :(得分:1)

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

添加变量ajaxcounter并将其设置为您要发送的文件数,您可以在上传时对它们进行计数,但这可能会带来在所有请求开始之前达到0的风险,您' d更好地对值进行硬编码,或者如果它是动态设置的,则将所有准备好的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
    }
}

希望它有所帮助,我没有测试它。