简体   繁体   中英

xhr.upload.onprogress doesn't work

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

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM