我创建了一个小部件,它使用 $.ajax() 调用从服务器获取数据。我允许用户在需要时从服务器刷新数据,因此我需要能够取消现有请求,以免与从服务器返回的多个数据集发生冲突。一次只能执行一个请求。
Widget Code
(function ($) {
$.widget("w.widgetName", {
options: { { /*set the widget options here*/ }},
_create: function () { /*do the create stuff here */ },
_cancelAjaxRequest: function(){//private method to cancel the current ajax request
var xhr = this.ajaxGetCall;
if (xhr && xhr.readyState != 4){
xhr.abort();//line that throws the error, but in the jQuery code
}
},
refresh: function () {
var self = this;
self._cancelAjaxRequest();
self.ajaxGetCall = $.ajax({//I assign the $.ajax() xhr object here
type: "POST",
contentType: "Application/json; charset=utf-8",
dataType: "json",
url: "url/goes/here",
data: dataGoesHere,
success: function (data) { /*Do stuff here*/},
error: function (xhr, status, error) { /*Do stuff here*/},
complete: function (r, s) { /*Do stuff here*/}
});
},
destroy: function () {
var self = this;
self._cancelAjaxRequest();
//do other stuff to destroy the object
}
});
} (jQuery));
同时使用 jQuery 1.8.2 和 1.9.1,在执行xhr.abort();
.
TypeError: Cannot read property 'length' of undefined
我放了 jQuery 1.8.2 和 1.9.1 的完整版本,它们都指向第 622 行。
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
//remaining code removed for brevity
}
非常感谢我对我遇到的这个问题的任何帮助或见解!
更新:我一直在做一个console.log(xhr)
仔细检查并确保我得到了一个xhr
对象。这是来自 Chrome 控制台的复制和粘贴。
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 0
setRequestHeader: function ( name, value ) {
state: function () {
status: 0
statusCode: function ( map ) {
statusText: "abort"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object