[英]Abort AJAX file upload by pressing escape key
我正在嘗試abort()
AJAX 文件上傳。 我已經嘗試添加事件偵聽器,並嘗試為任何keypress
都abort()
,盡管我在控制台中沒有看到任何內容。 這必須在沒有任何框架的情況下完成。
function myFunction()
{
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('keydown',function(e)
{
//if (e.keyCode==27) {}
xhr.abort();
console.log('escape, abort 1?');
},false);
xhr.addEventListener('keydown',function(e)
{
//if (e.keyCode==27) {}
xhr.abort();
console.log('escape, abort 2?');
},false);
}
嘗試將事件附加到window
對象:
var xhr = new XMLHttpRequest();
// ...
window.addEventListener('keydown',function(e) {
if (e.keyCode==27) {
xhr.abort();
}
}, false);
七年后,我看到了我的舊帖子,並決定自己嘗試弄清楚。 可以嵌入window
事件監聽器; 相關代碼行位於函數的底部,在 Waterfox 和 Chrome 中運行良好。
function ajax_promise(method,url)
{
var xhr = new XMLHttpRequest();
return new Promise(function (resolve, reject)
{
xhr.onabort = function()
{
alert('xhr aborted!');
}
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200) {resolve(xhr);}
else {reject({status: xhr.status, statusText: xhr.statusText});}
}
};
window.onkeydown = function(event) {if (event.key && event.key == 'Escape') {xhr.abort();}}
xhr.open(method, url, true);
xhr.send();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.