-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path封装ajax.html
166 lines (151 loc) · 5.78 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
/**
* ajax 01234 代表的翻译
0 - (未初始化)还没有调用send()方法
1 - (载入)已调用send()方法,正在发送请求
2 - (载入完成)send()方法执行完成,已经接收到全部响应内容
3 - (交互)正在解析响应内容
4 - (完成)响应内容解析完成,可以在客户端调用了
* **/
function getJson({
url,
params,
method
}) {
let promise = new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
let data = "";
for (const key in params) {
data += `${key}=${params[key]}&`
}
if (method.toLowerCase() === "get") {
xhr.open(method, url + "?" + data.substring(0, data.length - 1), true);
xhr.setRequestHeader("Accept", "application/json");
xhr.send(null);
} else if (method.toLowerCase() === "post") {
xhr.open(method, url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(data.substring(0, data.length - 1));
}
xhr.responseType = "json";
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
if (/^(2|3)\d{2}$/.test(xhr.status)) {
resolve(xhr.response);
} else {
reject(new Error(xhr.statusText));
}
}
xhr.onerror = function () {
reject(new Error(xhr.statusText));
}
})
return promise;
}
getJson({
url: "ajax.json",
method: "get",
params: {
name: "qc",
age: 18
}
}).then((res) => {
console.log(res);
}).catch(error => {
console.log(error);
})
// function getJson({
// url,
// params,
// method
// }) {
// return new Promise((resolve,reject)=>{
// let xhr=new XMLHttpRequest();
// let data="";
// for (const key in params) {
// data=`${key}=${params[key]}&`;
// }
// if(method.toLowerCase()==="get"){
// xhr.open(method,url+"?"+data.slice(0,data.length-1),true);
// xhr.setRequestHeader("Accept", "application/json");
// xhr.send(null);
// }else if(method.toLowerCase()==="post"){
// xhr.open(method,url,true);
// xhr.setRequestHeader("Accept", "application/json");
// xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
// xhr.send(data.slice(0, data.length - 1));
// }
// xhr.responseType = "json";
// xhr.onreadystatechange = function () {
// if (xhr.readyState !== 4) return;
// if (xhr.status === 200) {
// resolve(xhr.response);
// } else {
// reject(new Error(xhr.statusText));
// }
// }
// xhr.onerror = function () {
// reject(new Error(xhr.statusText));
// }
// });
// }
function ajax(options) {
//设置默认对象
var defaults = {
type: 'get',
url: '',
data: {},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function () {},
error: function () {}
};
//将传入参数对象与默认对象合并
Object.assign(defaults, options);
var params = '';
for (var attr in defaults.data) {
params += attr + '=' + defaults.data[attr] + '&';
}
params = params.substr(0, params.length);
if (defaults.type == 'get') {
defaults.url = defaults.url + '?' + params;
}
var xhr = new XMLHTTPRequest();
xhr.open(defaults.type, defaults.url);
if (defaults.type == 'post') {
var contentType = defaults.headers['Content-Type'];
xhr.setResquestHeader('Content-Type', contentType);
if (contentType == 'application/json') {
xhr.send(JSON.stringify(defaults.data));
} else {
xhr.send(params);
}
} else {
xhr.send();
}
xhr.onload = function () {
var contentType = xhr.getResquestHeader('Content-Type');
var responseText = xhr.responseText;
if (contentType.includes('application/json')) {
responseText = JSON.parse(responseText);
}
if (xhr.status == 200) {
defaults.success(responseText, xhr);
} else {
defaults.error(responseText, xhr);
}
}
}
</script>
</head>
<body>
</body>
</html>