let xhr = $.ajax({
url: url,
type: "POST",
dataType: 'json',
data: JSON.stringify({}),
headers: {'Content-Type': 'application/json'},
timeout: 10000, // 设定超时
cache: false, // 禁用缓存
error: function (e) {
console.log(e);
},
success: function (e) {
console.log(e);
},
async: true // 异步
})
xhr.abort();
$.get()、$.post、$.ajax、$.getJSON、$.getScript 返回值都是 XMLHttpRequest 对象;
XMLHttpRequest 对象有 abort() 方法
注意:abort()后,ajax请求立即停止,但还是会执行后面的方法。
以上代码:error 回调仍会执行,输出 e(e 对象有一个属性:statusText: "abort" )。
let commonRequestService = {
xhrCache: {
xhrPool: [],
_add: function (xhr) {
this.xhrPool.push(xhr);
},
_remove: function (xhr) {
this.xhrPool.remove(xhr);
},
abortAll: function () {
for (let i = 0, l = this.xhrPool.length; i < l; i++) {
try {
let xhr = this.xhrPool.shift();
if (xhr && typeof xhr.abort == 'function') xhr.abort();
} catch (error) {
console.log("Abort XHR: ", error);
}
}
this.xhrPool = [];
},
ajax: function (data) {
let that = this;
let xhr;
let successCallBack = data.success || function () {
};
let errorCallBack = data.error || function () {
};
data.success = function () {
// do otherthings
that._remove(xhr);
// successCallBack.apply(null, arguments);
successCallBack(...arguments);
};
data.error = function () {
// do otherthings
that._remove(xhr);
// errorCallBack.apply(null, arguments);
errorCallBack(...arguments);
};
xhr = $.ajax(data);
this._add(xhr);
},
serviceGet: function () {
},
servicePost: function (url, queryCon, callBack) {
this.ajax({
url: url,
type: "POST",
dataType: 'json',
data: JSON.stringify(queryCon),
headers: { 'Content-Type': 'application/json' },
timeout: 3000, // 设定超时
cache: false, // 禁用缓存
error: function (e) {
},
success: function (e) {
},
async: true // 异步
})
}
},
// 终止所有请求
abortAllRequest: function () {
this.xhrCache.abortAll();
},
};
缓存相关:
- Ajax 页面缓存是 ajax 处理数据时对一些重复相同数据进行一个缓存操作,这种设计使客户端对一些静态页面内容的请求,比如图片,css文件,js脚本等,变得更加快捷,提高了页面的响应速度,也节省了网络通信资源
- 有时候如果通过 ajax 对一些后台数据进行更改的时候,虽然数据在后台已经发生改变,但是页面缓存中并没有改变,对于相同的URL,ajax 提交过去以后,浏览器还只是简单的从缓存中拿数据