中止xmlhttprequest演示

问题描述 投票:15回答:4

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

干杯

javascript html5 xmlhttprequest
4个回答
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/


2
投票

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

this.abort();

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

0
投票

您可以使用AbortController和fetch来中止请求。

Demo

Code

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();
});
© www.soinside.com 2019 - 2024. All rights reserved.