JQuery封装一个属于自己的ajax函数,课提高代码的复用率。

1. 通用型ajax方法

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
/**
* ajax封装
* url 发送请求的地址
* data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1}
* async 默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。
* 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
* type 请求方式("POST" 或 "GET"), 默认为 "GET"
* dataType 预期服务器返回的数据类型,常用的如:xml、html、json、text
* successfn 成功回调函数
* errorfn 失败回调函数
*/
jQuery.ajx = function(url, data, async, type, dataType, successfn, errorfn) {
async = (async == null || async == "" || typeof(async) == "undefined") ? "true" : async;
type = (type == null || type == "" || typeof(type) == "undefined") ? "get" : type;
dataType = (dataType == null || dataType == "" || typeof(dataType) == "undefined") ? "json" : dataType;
data = (data == null || data == "" || typeof(data) == "undefined") ? {
"date": new Date().getTime()
} : data;
$.ajax({
type: type,
async: async,
data: data,
url: url,
dataType: dataType,
contentType: "application/json",
success: function(data,status) {
successfn(data,status);
},
error: function(xhr,err) {
errorfn(xhr,err);
}
});
};

2. GET方式ajax方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* ajax Get封装
* url 发送请求的地址
* dataType 返回数据类型
* successfn 成功回调函数(d数据、txt状态码)
* errorfn 失败回调(xhr http对象、e错误码)
*
*/
jQuery.ajxGet = function(url, dataType, successfn, errorfn) {
$.ajax({
type: "get",
url: url,
dataType: dataType,
success: function(data,status) {
successfn(data,status);
},
error: function(xhr,err) {
errorfn(xhr,err);
}
});
};

3. POST方式ajax方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
*
* url 数据发送地址
* data 发送数据
* dataType 返回数据类型
* successfn 成功回调
* errorfn 失败回调
*/
jQuery.ajxPost = function(url,data,dataType,successfn,errorfn){
$.ajax({
type: "post",
url: url,
data: data,
dataType: dataType,
contentType: "application/json",
success: function(d,txt) {
successfn(d,txt);
},
error: function(xhr,e) {
errorfn(xhr,e);
}
});
};