重写ajax方法
2026-05-02 18:28:33
199
分类:javascript
对$.ajax重写,增强处理
// 首先备份下jquery的ajax方法
var _ajax = $.ajax;
// 重写jquery的ajax方法
$.ajax = function (options) {
var _opt = {
beforeSend: function (xhr) {
if (options.beforeSend) options.beforeSend(xhr);
},
success: function (result, status, xhr) {
if (options.success) options.success(result, status, xhr);
},
error: function (xhr, status, error) {
switch (xhr.status) {
case 403:
layer.alert('服务器拒绝提供服务', {icon: 2, title: '错误信息'});
break;
case 404:
layer.alert('请求的资源不存在', {icon: 2, title: '错误信息'});
// location.href = '404.html';
break;
case 500:
layer.alert('服务器发生不可预期的错误', {icon: 2, title: '错误信息'});
// location.href = '500.html';
break;
case 503:
layer.alert('服务器繁忙,请稍后再试', {icon: 2, title: '错误信息'});
break;
}
if (options.error) options.error(xhr, status, error);
},
complete: function (xhr, status) {
if (options.complete) options.complete(xhr, status);
}
};
// 返回重写的ajax
return _ajax($.extend({}, _opt, options));
};不重新$.ajax,重新options
var utils = {
ajax: function (options) {
var _opt = {
beforeSend: function (xhr) {
if (options.beforeSend) return options.beforeSend(xhr);
},
success: function (result, status, xhr) {
// 登录过期
// if (result != undefined && result.statusCode === "1000") {
// location.href = "index.html";
// }
if (options.success) return options.success(result, status, xhr);
},
error: function (xhr, status, error) {
switch (xhr.status) {
case 403:
layer.alert('服务器拒绝提供服务', {icon: 2, title: '错误信息'});
break;
case 404:
layer.alert('请求的资源不存在', {icon: 2, title: '错误信息'});
// location.href = '404.html';
break;
case 500:
layer.alert('服务器发生不可预期的错误', {icon: 2, title: '错误信息'});
// location.href = '500.html';
break;
case 503:
layer.alert('服务器繁忙,请稍后再试', {icon: 2, title: '错误信息'});
break;
}
if (options.error) return options.error(xhr, status, error);
},
complete: function (xhr, status) {
if (options.complete) return options.complete(xhr, status);
}
};
var _options = $.extend({}, options, _opt);
$.ajax(_options);
}
}