xhr.upload.onprogress不起作用 [英] xhr.upload.onprogress doesn't work

查看:840
本文介绍了xhr.upload.onprogress不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码中的所有内容都可以使用,但它永远不会触发xhr.upload.onprogress事件。

Everything in the following code will work, except it will never fire the xhr.upload.onprogress event.

$(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
        }
    });
}); 


推荐答案

您应该在打开连接之前创建侦听器,例如这个:

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

希望有所帮助。

这篇关于xhr.upload.onprogress不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆