中止xmlhttprequest

时间:2011-10-29 16:42:10

标签: javascript html5 xmlhttprequest

我正在使用HTML5上传文件。我有一个附加到函数uploadFile()的按钮单击事件。它工作正常。我还有一个单独的按钮来取消上传。我知道我们需要调用xhr.abort()但是如何访问uploadCanceled函数中的xhr对象?我可以使xhr对象全局化,但这不是正确的方法。有人可以在这里指导我吗?

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

干杯

4 个答案:

答案 0 :(得分:16)

addEventListener会将this的上下文(uploadCanceled)设置为xhr

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

示例:http://jsfiddle.net/wJt8A/


相反,如果您需要通过“取消”点击触发xhr.abort,则可以在此之后返回引用并添加所需的任何侦听器:

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

示例:http://jsfiddle.net/rC63r/1/

答案 1 :(得分:2)

您应该能够在cancelUpload事件处理程序中引用“this”关键字。这指的是XMLHttpRequest。把它放在处理程序中:

this.abort();

答案 2 :(得分:0)

中止所有XMLHttpRequest:

var array_xhr = new Array();
function uploadFile(){ 
    ...
    var xhr = new XMLHttpRequest(); 
    array_xhr.push(xhr);
    ...
}

function abort_all_xhr(){
  if (array_xhr.length>0) {
        for(var i=0; i<array_xhr.length; i++){
            array_xhr[i].abort();
        }
        array_xhr.length = 0;
    };
}

abort_all_xhr();

答案 3 :(得分:0)

您可以使用AbortController并提取以中止请求。

Demo

代码

const btn = document.getElementById('btn');
const btn2 = document.getElementById('btn2');
const url = 'https://www.mocky.io/v2/5185415ba171ea3a00704eed?mocky-delay=1000ms';

const ctrl;

btn.addEventListener('click', e => {
  ctrl = new AbortController();
  const signal = ctrl.signal;

  fetch(url, { signal })
    .then(r => r.json())
    .then(r => {
      console.log('Request result', r);
    }).catch(e => {
      console.error('Request was aborted. Error:', e);
    })
});

btn2.addEventListener('click', e => {
  ctrl.abort();
});