Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

javascript - JQuery Access XMLHttpRequest?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...