xhr.upload.onprogress不起作用

use*_*664 8 javascript xmlhttprequest-level2

以下代码中的所有内容都可以使用,除非它永远不会触发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
        }
    });
}); 
Run Code Online (Sandbox Code Playgroud)

Voi*_*ain 16

您应该在打开连接之前创建侦听器,如下所示:

$(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);
    });
});
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

  • 您可以在处理程序之前打开连接,但发送需要在之后. (7认同)