2013-05-29 30 views
0

我有一個代碼,適用於通過Ajax與FormData和XMLHttpRequest發送多個文件;如何知道所有上傳是在循環內完成的?

  for (var i=0, j=this.files.length; i<j; i++) { 
      file = this.files[i]; 

      var formdata = new FormData();   
       formdata.append("images[]", file); 


      var xhr = new XMLHttpRequest(), 
       upload = xhr.upload, 
       id = Math.floor((Math.random() * 100000)); 

       upload.addEventListener("loadstart", function(e){ 
         showUploadedItem(file, this.id); 
       }); 
       upload.id = id; 
       upload.onprogress = function(e) { 
        var done = e.position || e.loaded, total = e.totalSize || e.total; 
        ) 
       }; 
       upload.onload = function(e) { 

        if (this.status == 200) { 
         console.log(''); 
        }       
       }; 
       xhr.onreadystatechange = function(e) { 
        if (4 == this.readyState) { 
         console.log(''); 
        } 
       }; 
       xhr.open('post', '<?php echo Yii::app()->createUrl('url') ?>', true); 
       xhr.send(formdata);      
     } 

我發送每個文件作爲環內一個新的XMLHttpRequest對象,所以當我收到結尾的請求,我不知道。

任何人都可以幫忙嗎?

回答

1

查看XMLHttpRequest的文檔。

有幾個我可以想到的選項。你可以對它們中的每一個使用「loadend」回調,並在循環外部增加一個變量,並檢查每個請求發送的請求總數。一旦計數達到請求的總數,您可以執行任何邏輯或調用想要調用的函數。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest%2FUsing_XMLHttpRequest

否則,async參數設置爲false,將工作爲好,但你採取的性能損失等待每一個在開始別人之前完成。

0

根據你的回答,我的解決方案;

 var x = 0; 
     var lenght = this.files.length; 
     for (var i=0, j=lenght; i<j; i++) { 

     // code here     

      var xhr = new XMLHttpRequest(), 

      // code here 

       xhr.onreadystatechange = function(e) { 
        if (4 == this.readyState && this.status == 200) { 
         x++; 
         if(x == lenght) { 
          window.setTimeout(function(){ 
           alert('finish'); 
          }, 1000); 
         } 
        } 
       }; 
      // code here 
      } 

雖然它是一個平凡的功能,它的工作原理。

+0

你可能甚至不需要setTimeout。 – jwebb

相關問題