-
Notifications
You must be signed in to change notification settings - Fork 0
/
Promise封装ajax.js
60 lines (59 loc) · 1.8 KB
/
Promise封装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
/**
* 使用 Promise 封装 Ajax
*
* @param {String} url 请求地址
* @param {String} method 请求方法 默认 get
* @param {Object} params 请求参数 默认 {}
* @param {Boolean} async 是否异步 默认 true
*/
const ajax = (url, method = "get", params = {}, async = true) =>
new Promise((resolve, reject) => {
const getParamString = params => {
let dataString = "";
for (const key in params) {
dataString += `${key}=${params[key]}&`;
}
return dataString;
};
const paramString = getParamString(params);
if (["get", "GET"].includes(method) && paramString) {
url.indexOf("?") > -1 ? (url += paramString) : (url += `?${paramString}`);
}
const xhr = XMLHttpRequest
? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
xhr.open(method, url, async);
xhr.onload = function() {
const result = {
status: this.status,
statusText: this.statusText,
headers: this.getAllResponseHeaders(),
data: this.response || this.responseText
};
if ((this.status >= 200 && this.status < 300) || this.status === 304) {
resolve(result);
} else {
reject(result);
}
};
xhr.setRequestHeader(
"Content-type",
params.contentType || "application/x-www-form-urlencoded"
);
xhr.responseType = params.responseType || "json";
xhr.withCredentials = params.withCredentials || true;
xhr.onerror = function() {
reject(new TypeError("Request error"));
};
xhr.timeout = function() {
reject(new TypeError("Request timeout"));
};
xhr.onabort = function() {
reject(new TypeError("Request terminated"));
};
if (["post", "POST"].includes(method)) {
xhr.send(paramString);
} else {
xhr.send();
}
});