簡體   English   中英

xmlhttprequest在函數中無法正常工作

[英]xmlhttprequest does not work properly in function

有人知道為什么upload.onprogress如果在單獨的函數上不能正常工作?

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

        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;
             }
        }   

使用uploadProgress(event); 您調用函數本身並將返回值xhr.upload.onprogress而不是將其指定為回調函數:

xhr.upload.onprogress = uploadProgress;

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

xhr.upload.onprogress = uploadProgress;

xhr.upload.onprogress = uploadProgress(event);

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

如何在分配回調之前定義函數? 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;

暫無
暫無

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

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