-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path封装ajax.html
90 lines (80 loc) · 2.76 KB
/
封装ajax.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax Promise</title>
</head>
<body>
<div id='root'></div>
</body>
<script>
function ajax(options = {
url: '',
method: 'GET',
data: {},
timeout: 60,
}) {
options.method = (options.method || 'GET').toUpperCase();
const paramString = formatParams(options.data);
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.timeout = (options.timeout || 60) * 1000
if (options.method === "GET") {
let url = options.url + (options.url.indexOf('?') > -1 ? '&' : "?") + paramString
xhr.open("GET", url);
// xhr.setRequestHeader("User-Agent", "Mozilla/5.0 (Linux; X11)");
xhr.send(null);
}
if (options.method === "POST") {
xhr.open("POST", options.url);
// 设置请求头
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// 跨域携带cookie
// xhr.withCredentials = true;
xhr.send(paramString);
}
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.onerror = function () {
reject(new TypeError("请求出错"));
};
xhr.ontimeout = function () {
reject(new TypeError("请求超时"));
};
xhr.onabort = function () {
reject(new TypeError("请求被终止"));
};
});
}
function formatParams(data) {
let arr = [];
for (var key in data) {
if (data.hasOwnProperty(key)) arr.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
return arr.join("&");
}
ajax({
url: 'https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started?a=b',
method: 'get',
data: { name: '测试', age: 20 },
timeout: 10,
}).then((res) => {
console.log(res)
document.getElementById('root').innerHTML = res.data
})
</script>
</html>