原生js封装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
34
35
36
37
38
39
function ajax (options) {
let xhr = null
if ((window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
// IE6及其以下版本
xhr = new ActiveXObjcet('Microsoft.XMLHTTP');
}
xhr.onreadystatechange = function () {
if(xhr.readyState == 4) {
let status = xhr.status;
if ((status >= 200 && status < 300) || status === 304) {
options.success && options.success()
} else {
options.error && options.error()
}
}
}
let type = (options.type || 'GET').toUpperCase() // 转为大写
if (type === 'GET') {
let url = xhr.url + '?' + formatParams(option.data)
xhr.open(type, url, true)
xhr.send(null)
} else {
xhr.open(type, url, true)
//设置提交时的内容类型
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(option.data)
}
function formatParams (data) {
var arr = [];
for(var name in data) {
arr.push(name + '=' + data[name]);
};
// 添加一个随机数,防止缓存
arr.push('v=' + Math.floor(Math.random() * 10000 + 500));
return arr.join('&');
}
}