-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajax.js
50 lines (49 loc) · 1.37 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
function ajax(url, method = "get", param = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const paramString = getStringParam(param);
if (method === "get" && paramString) {
url.indexOf("?") > -1 ? (url += paramString) : (url += `?${paramString}`);
}
xhr.open(method, url);
xhr.onload = function() {
const result = {
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders(),
data: xhr.response || xhr.responseText
};
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
resolve(result);
} else {
reject(result);
}
};
// 设置请求头
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// 跨域携带cookie
xhr.withCredentials = true;
// 错误处理
xhr.onerror = function() {
reject(new TypeError("请求出错"));
};
xhr.timeout = function() {
reject(new TypeError("请求超时"));
};
xhr.onabort = function() {
reject(new TypeError("请求被终止"));
};
if (method === "post") {
xhr.send(paramString);
} else {
xhr.send();
}
});
}
function getStringParam(param) {
let dataString = "";
for (const key in param) {
dataString += `${key}=${param[key]}&`;
}
return dataString;
}