Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

javascript - Aborting the xmlhttprequest

I am using HTML5 for uploading files. I have a button click event attached to the function uploadFile(). It works fine. I also have a separate button to cancel the upload. I know we need to call xhr.abort() but how do I access the xhr object in the uploadCanceled function? I can make the xhr object global but that is not the proper way. Can someone guide me here?

function uploadFile(){ 
    var filesToBeUploaded = document.getElementById("fileControl"); 
    var file = filesToBeUploaded.files[0]; 
    var xhr= new XMLHttpRequest(); 
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);


    xhr.open("POST", "upload.php", true); 

    var fd = new FormData();
    fd.append("fileToUpload", file);
     xhr.send(fd); 
}


    function uploadCanceled(evt) {
        alert("Upload has been cancelled");
    } 

Cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

addEventListener will set the context (this) of uploadCanceled to xhr:

function uploadCanceled(evt) {
    console.log("Cancelled: " + this.status);
}

Example: http://jsfiddle.net/wJt8A/


If, instead, you need to trigger xhr.abort through a "Cancel" click, you can return a reference and add any listeners you need after that:

function uploadFile() {
    /* snip */
    xhr.send(fd);

    return xhr;
}

document.getElementById('submit').addEventListener('click', function () {
    var xhr = uploadFile(),
        submit = this,
        cancel = document.getElementById('cancel');

    function detach() {
        // remove listeners after they become irrelevant
        submit.removeEventListener('click', canceling, false);
        cancel.removeEventListener('click', canceling, false);
    }

    function canceling() {
        detach();
        xhr.abort();
    }

    // detach handlers if XHR finishes first
    xhr.addEventListener('load', detach, false);

    // cancel if "Submit" is clicked again before XHR finishes
    submit.addEventListener('click', canceling, false);

    // and, of course, cancel if "Cancel" is clicked
    cancel.addEventListener('click', canceling, false);
}, false);

Example: http://jsfiddle.net/rC63r/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...