Javascript 中止 xmlhttprequest
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7940213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Aborting the xmlhttprequest
提问by lewis
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?
我正在使用 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");
}
Cheers
干杯
回答by Jonathan Lonowski
addEventListener
will set the context (this
) of uploadCanceled
to xhr
:
addEventListener
将上下文 ( this
) 设置uploadCanceled
为xhr
:
function uploadCanceled(evt) {
console.log("Cancelled: " + this.status);
}
Example: http://jsfiddle.net/wJt8A/
示例: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:
相反,如果您需要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);
Example: http://jsfiddle.net/rC63r/1/
回答by dnuttle
You should be able to reference the "this" keyword in your canceledUpload event handler. That refers to the XMLHttpRequest. Put this in the handler:
您应该能够在 cancelledUpload 事件处理程序中引用“this”关键字。那是指 XMLHttpRequest。把它放在处理程序中:
this.abort();
回答by Hyman
Abort all XMLHttpRequest:
中止所有 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();
回答by WebBrother
You can use AbortControllerand fetch to abort requests.
您可以使用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();
});