Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The JQuery ajax documentation said that you can get access to the XMLHttpRequest by the following:

var jqxhr = $.ajax({
      xhr: function() {
          var xhrNativeObject = new window.XMLHttpRequest();
          xhrNativeObject.upload.addEventListener("progress", function(event) { 
               // progress bar 
          }, false);
          return xhrNativeObject;
      },
      url: url,
  type: "POST",
  data: formdata,
  processData: false,
  contentType: false
    }).then(function(response) { 
         ...         
    });
   jqxhr.abort();  // this is not working!!!

This is not working for me when I print jqxhr in my console I get:

Object {url: "http://someurl", isLocal: false, global: true, type: "POST", contentType: false…} 

I only get the XMLHttpRequest when I do the following:

var myXHR;
$.ajax({
   xhr: function() { 
      myXHR = new window.XMLHttpRequest(); 
   }
 ... });

When I print myXHR on my console I get:

XMLHttpRequest {open: function, setRequestHeader: function, send: function, abort: function, getAllResponseHeaders: function…}

This is correct.

The JQuery docu said that I can do abort() on the jqxhr object. When do do:

jqxhr.abort();

I get the following console error:

Uncaught TypeError: Object #<Object> has no method 'abort'

When I do

myXHR.abort();

everything is working.

Why is abort() not working on the jqxhr object?

Edit: Using JQuery 1.8.3

Edit: I created an example: http://jsfiddle.net/9HmQd/ It turns out that abort is undefined when I add the then() block.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
232 views
Welcome To Ask or Share your Answers For Others

1 Answer

When you use .ajax(), it returns a special kind of promise which is the jqXHR object, but when you call then on the jqxhr, it returns a promise object which will not have methods associated with jqXhr - in your case this promise is the value assigned to the xhr variable because of chaining.

Solution

var xhr = $.ajax({
    url: '/echo/json'
});
xhr.then(function (response) {})

console.log(xhr.abort);

Demo: Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...