-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ajax.js
100 lines (94 loc) · 3.25 KB
/
Ajax.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var _ = (function() {
return {
getXhr: function() {
// 适配IE各版本
if(!new XMLHttpRequest()) {
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {}
return false;
}
}
// 适配主流浏览器
return new XMLHttpRequest();
},
// 参数序列化
serialize: function(url,data) {
if(!data) return url;
for (var name in data) {
if (!data.hasOwnProperty(name)) continue;
if (typeof data[name] === 'function') continue;
var value = data[name].toString();
name = encodeURIComponent(name);
value = encodeURIComponent(value);
url += (url.indexOf("?") == -1 ? "?" : "&");
url += name + "=" + value;
}
return url;
},
setRequestHeader: function(xhr, headers) {
if(!headers) {
xhr.setRequestHeader(
'Content-Type', 'application/x-www-form-urlencoded'
);
return;
}
for (var name in headers) {
xhr.setRequestHeader(
name.toString(), headers[name].toString()
);
}
},
ajax: function(options) {
var xhr = this.getXhr();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
options.callback(xhr.responseText);
} else {
if(options.error) options.error(xhr.responseText);
console.log('错误代码:' + xhr.responseText);
}
}
}
if (options.method.toUpperCase() === 'GET' || 'DELETE') {
var url = this.serialize(options.url,options.data)
xhr.open(options.method.toUpperCase(), url, true);
this.setRequestHeader(xhr, options.header);
xhr.send(null);
} else if (options.method.toUpperCase() === 'POST' || 'PATCH') {
xhr.open(options.method.toUpperCase(), options.url, true);
this.setRequestHeader(xhr, options.header);
xhr.send(JSON.stringify(options.data));
} else {
console.log('不识别的方法:' + options.method);
return fasle;
}
}
}
})()
/*
加*为必传的参数,其它都是可选的
_.ajax({
url: '/api/test', // *
method: 'GET/POST/DELETE/PATCH', // *
data: {
name: 'xxx',
id: 001
},
header: {
contenttype: 'application/json'
},
callback: function(data) {
console.log('ok')
},
error: function(data) {
console.log('falser' + data)
}
})
*/