I'm trying to abort() an AJAX file upload. I've tried adding event listeners and am trying to abort() for any keypress at all though I'm not seeing anything in the console. This must be done without any frameworks.

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);
}
有帮助吗?

解决方案 2

Seven years later I came across my old post and decided to try and figure it out myself. It is possible to embed the window event listener; the relevant line of code is at the bottom of the function and works fine in Waterfox and 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();
 });
}

其他提示

Try to attach event to window object instead:

var xhr = new XMLHttpRequest();
// ...
window.addEventListener('keydown',function(e) {
    if (e.keyCode==27) {
        xhr.abort();
    }
}, false);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top