문제

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