[英]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.