문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top