重写JQuery的Ajax请求实现公用功能,如:权限判断

1.前言

Loding加载层

我们做JAVA开发的,管理系统做的比较多,管理系统大多都有一个特点:单页面应用SPA
(Single Page Application),单页面程序就会用很多的Ajax异步请求后台查询数据,为了用户体验,我们都会在发送请求的时候加载一个Loding..提示层


又或者是用户掉线了,点击发送请求时会跳回到登录页面重新登录等等,一系列在发送请求时都要做的事情可以重写ajax实现每次发送ajax请求都将执行公用方法

2.重写Ajax

新建reAjax.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
$(function(){
var layer;//layer弹窗插件,用于页面提示
var index;
layui.use('layer', function(){
layer= layui.layer;
});
(function($){

//首先备份下jquery的ajax方法
var _ajax=$.ajax;

//重写jquery的ajax方法
$.ajax=function(opt){
//备份opt中error和success方法
var fn = {
error:function(XMLHttpRequest, textStatus, errorThrown){},
success:function(data, textStatus){}
}
if(opt.error){
fn.error=opt.error;
}
if(opt.success){
fn.success=opt.success;
}

//扩展增强处理
var _opt = $.extend(opt,{
error:function(XMLHttpRequest, textStatus, errorThrown){
//错误方法增强处理
layer.alert('连接服务器失败,请稍后重试!')
fn.error(XMLHttpRequest, textStatus, errorThrown);
},
success:function(data, textStatus){
if(data.code == 888){
layer.alert('未登录,请重新登录!',function(){
window.location.href='/login.html';
});
return false;
}

if(data.code == 666){
layer.alert('无权限访问!');
return false;
}
//成功回调方法增强处理
fn.success(data, textStatus);
},
beforeSend:function(XHR){
//提交前回调方法
index = layer.load(0);

},
complete:function(XHR, TS){
//请求完成后回调函数 (请求成功或失败之后均调用)。
layer.close(index);
}
});
return _ajax(_opt)
};
})(jQuery);
});

传统页面直接引入该js就行,缺点是每个页面都要引一次


如果用的webpack打包:直接加入依赖即可

1
2
3
4
5
6
7
8
9
10
11
12
13
resolve:{
alias: {
avalon2: path.resolve(PATHS.node_modulesPath, "avalon2/dist/avalon.js"),
//ueditor: path.resolve(PATHS.node_modulesPath, "ueditor/example/public/ueditor"),
bootstrap: path.resolve(PATHS.node_modulesPath, 'bootstrap/dist'),
jquery: path.resolve(PATHS.libPath, 'jquery-1.12.4.js'),
//这里全局引入即可
reAjax: path.resolve(PATHS.libPath, 'reAjax.js'),
mmRouter: path.resolve(PATHS.node_modulesPath, "mmRouter/dist/mmRouter.js")
},
modules: [path.resolve(__dirname, "src/static/lib"), "node_modules", "src/tpl"]
},
...