簡體   English   中英

等到ajax完成

[英]Wait until ajax is done

我有這樣的代碼:

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將被調用。

有解決方案嗎

謝謝

當XHR調用完成時,它會使用readyState == 4觸發onreadystatechange 。所以你需要為該事件分配一個函數,而不是onload

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

        console.log(xhr.responseText);

    }
}

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

添加變量ajaxcounter並將其設置為您要發送的文件數,您可以在上傳中對它們進行計數,但這可能會帶來在所有請求啟動之前達到0的風險,您最好對該值進行硬編碼,或者如果它是動態設置的,則將所有准備好的XHR存儲在一個數組中,並在您知道自己擁有所有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
    }
}

希望它有所幫助,我沒有測試它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM