javascript xhr.upload.onprogress 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14160308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:52:53 来源:igfitidea点击:
xhr.upload.onprogress doesn't work
提问by user1534664
Everything in the following code will work, except it will never fire the xhr.upload.onprogress event.
以下代码中的所有内容都将起作用,除了它永远不会触发 xhr.upload.onprogress 事件。
$(function(){
var xhr;
$("#submit").click(function(){
var formData = new FormData();
formData.append("myFile", document.getElementById("myFileField").files[0]);
xhr = new XMLHttpRequest();
xhr.open("POST", "./test.php", true);
xhr.send(formData);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText);
}
}
xhr.upload.onprogress = function(e) {
// it will never come inside here
}
});
});
回答by VoidMain
You should create the listeners before opening the connection, like this:
您应该在打开连接之前创建侦听器,如下所示:
$(function(){
var xhr;
$("#submit").click(function(){
var formData = new FormData();
formData.append("myFile", document.getElementById("myFileField").files[0]);
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText);
}
}
xhr.upload.onprogress = function(e) {
// it will never come inside here
}
xhr.open("POST", "./test.php", true);
xhr.send(formData);
});
});
Hope that helps.
希望有帮助。