2012-03-14 18 views
4

有誰知道爲什麼upload.onprogress在單獨函數中無法正常工作?xmlhttprequest在函數中無法正常工作

代碼正常工作(進度條緩慢移動):

 xhr.upload.onprogress = function(e) { 
      if (e.lengthComputable) { 
       progress.value = (e.loaded/e.total) * 100; 
      } 
     }; 

,但如果我把它改成功能,它不工作了:

xhr.upload.onprogress = uploadProgress(event); 

function uploadProgress(e) { 
    if (e.lengthComputable) { 
     progress.value = (e.loaded/e.total) * 100; 
    } 
} 

在第二個代碼,進度在上傳文件完成上傳後,直接跳到100%,上傳時很好地移動到100%


所以,我試過提供的解決方案,它實際上工作,如果我把裏面的功能。有沒有辦法把它放在功能之外?

 function uploadFile(blobFile, fileName) { 
      ... 
      ... 

      // Listen to the upload progress for each upload. 
      xhr.upload.onprogress = uploadProgress; 

      // Progress Bar Calculation why it has to be in uploadFile function.. 
      function uploadProgress(e) { 
       if (e.lengthComputable) { 
        progress.value = (e.loaded/e.total) * 100; 
       } 
      }        

      uploaders.push(xhr); 
      xhr.send(fd); 
     } 

     //it does not work if I put it outside the function. is there anyway to do this? 
     function uploadProgress(e) { 
      if (e.lengthComputable) { 
       progress.value = (e.loaded/e.total) * 100; 
      } 
     } 

回答

6

隨着uploadProgress(event);調用該函數本身和返回值賦給xhr.upload.onprogress不是作爲一個回調函數分配給它的:

xhr.upload.onprogress = uploadProgress; 
+0

你是對的..變量進步是uploadFile()內。這就是爲什麼它不起作用。在JavaScript中有沒有什麼好的做法,而不是將它作爲一個函數內部的函數..這在某種程度上看起來很糟糕。因爲 var progress = document.createElement('progress'); 應位於uploadFile()內部,因此每次調用時都會生成多個進度欄。因此,我不能讓它成爲全局變量var – Harts 2012-03-14 19:06:06

+0

@ user1096900您可以使用匿名函數:'xhr.upload.onprogress = function(e){}'或者只是一個匿名包裝函數:'xhr.upload.onprogress = function(e ){uploadProgress(e,progress);}'。 – ComFreek 2012-03-14 19:11:44

1

在第二個例子中,你應該使用

xhr.upload.onprogress = uploadProgress; 

不是

xhr.upload.onprogress = uploadProgress(event); 

您已經分配了調用該函數的結果,而不是對函數的引用。

+0

@ComFreek我試過,但它仍然無法正常工作。它在完成每個塊的上傳後仍然直接跳到100%。 – Harts 2012-03-14 18:35:31

+0

將函數後面放置xhr.upload.onprogress,提升可能是代碼中的一個因素。 – leebriggs 2012-03-14 18:40:36

+0

@ComFreek,請參閱我更新的代碼。那麼,有沒有把它放在功能之外呢?或者它不可能?謝謝 – Harts 2012-03-14 18:44:29

1

如何在分配回調之前定義函數?在稍後定義函數時,JavasCript有時會遇到問題。

我的意思是你可以替換:

// Listen to the upload progress for each upload. 
xhr.upload.onprogress = uploadProgress; 

// Progress Bar Calculation 
function uploadProgress(e) { 
    if (e.lengthComputable) { 
     progress.value = (e.loaded/e.total) * 100; 
    } 
} 

// Progress Bar Calculation 
function uploadProgress(e) { 
    if (e.lengthComputable) { 
     progress.value = (e.loaded/e.total) * 100; 
    } 
} 
// Listen to the upload progress for each upload. 
xhr.upload.onprogress = uploadProgress;