jQuery访问XMLHttpRequest吗? [英] JQuery Access XMLHttpRequest?
问题描述
JQuery ajax 文档表示,您可以通过以下方式访问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!!!
当我在控制台中打印jqxhr时,这对我不起作用:
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…}
执行以下操作时,我只会获得XMLHttpRequest:
I only get the XMLHttpRequest when I do the following:
var myXHR;
$.ajax({
xhr: function() {
myXHR = new window.XMLHttpRequest();
}
... });
当我在控制台上打印myXHR时,我得到:
When I print myXHR on my console I get:
XMLHttpRequest {open: function, setRequestHeader: function, send: function, abort: function, getAllResponseHeaders: function…}
这是正确的.
JQuery文档说我可以对jqxhr对象执行abort().何时做:
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'
我这样做
myXHR.abort();
一切正常.
为什么abort()在jqxhr对象上不起作用?
使用JQuery 1.8.3
Using JQuery 1.8.3
我创建了一个示例: http://jsfiddle.net/9HmQd/ 事实证明,当我添加then()块时,中止是不确定的.
I created an example: http://jsfiddle.net/9HmQd/ It turns out that abort is undefined when I add the then() block.
推荐答案
使用.ajax()
时,它返回一种特殊的承诺,即 promise 对象,该对象将不具有与jqXhr关联的方法-在您的情况下,此诺言是由于链接而分配给xhr
变量的值.
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.
解决方案
var xhr = $.ajax({
url: '/echo/json'
});
xhr.then(function (response) {})
console.log(xhr.abort);
演示:小提琴
这篇关于jQuery访问XMLHttpRequest吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!