-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path052js中的ajax
206 lines (153 loc) · 5.39 KB
/
052js中的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
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
一. 什么是ajax
异步的javascript and xml
是一种不需要刷新页面就可以从服务台请求数据的一种技术。
二. ajax的过程
1.新建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
2.调用open()方法,请求准备阶段
注意:调用open()方法时,并没有发送请求,只是启动一个请求以备发送。
xhr.open("请求的方法","请求的地址",是否发送异步请求);
GET请求:向服务器查询某些信息,把查询的字符串追加到URL末尾
POST请求:用于向服务器发送某些要保存的数据。
flase:请求不是异步
true:请求是异步的
3.调用send()方法,发送请求
xhr.send(null);
send()函数里面接收的参数,是作为请求主体发送的数据,如果不发送数据,那么必须将参数置为null
4.给xhr绑定一个状态变化的监听事件 onreadystatechange
为了满足跨浏览器的兼容性,必须在open事件调用之前指定onreadystatechange事件处理程序
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) //请求响应的当前活动阶段,4表示响应已完成
{
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304)
{alert(xhr.responseText);}
else
{alert("unsuccessful")}
}
}
服务器响应之后,XHR对象的4个属性值发生了变化
responseText:响应的内容
responseXML:响应的类型
status:响应的状态
statusText:响应状态的文字说明
readyState: ajax请求响应过程的当前活动阶段
根据响应状态status写相关的操作函数
status的几种取值:
200表示成功
304表示可以使用浏览器的缓存版本
204表示没有新文档
readyState的几种取值:
0:未调用open()
1:已调用open(),未调用send()
2:已调用send(),但没有接收到响应
3:已接收到部分响应数据
4:已接收到全部响应数据
在接收到响应之前取消异步请求的方法:
xhr.abort()
5.获取异步调用返回的数据
6.使用js和DOM实现局部刷新
--------------------------------------------------------------------------------------------------------------------------------
2018.05.01五一劳动节修改 常用的三种方案:
第一种方案:XMLHttpRequest
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
}
if (xhr) {
xhr.onreadystatechange = onReadyStateChange;
xhr.open('POST', '/api', true); // 设置 Content-Type 为 application/x-www-form-urlencoded
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 以表单的形式传递数据
xhr.send('username=admin&password=root');
}
// onreadystatechange 方法
function onReadyStateChange() {
// 该函数会被调用四次
console.log(xhr.readyState);
if (xhr.readyState === 4) {
// everything is good, the response is received
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('There was a problem with the request.');
}
} else {
// still not ready
console.log('still not ready...');
}
}
第二种方案
jQuery实现AJAX
$.ajax({
method: 'POST',
url: '/api',
data: { username: 'admin', password: 'root' }
})
.done(function(msg) {
alert( 'Data Saved: ' + msg );
});
第三种方案
Fetch
fetch(...).then(fun2)
.then(fun3) //各依赖有序执行
.....
.catch(fun)
(没有回调地狱)
fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin"
}).then(function(response) {
response.status //=> number 100–599
response.statusText //=> String
response.headers //=> Headers
response.url //=> String
return response.text()
}, function(error) {
error.message //=> String
})
链接 https://github.github.io/fetch/
---------------------------------------------------------------------------------------------------
20180919封装的ajax函数
function ajax(opt) {
opt = opt || {};
opt.method = opt.method.toUpperCase() || 'POST';
opt.url = opt.url || '';
opt.async = opt.async || true;
opt.data = opt.data || null;
opt.success = opt.success || function() {};
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
var params = [];
for (var key in opt.data) {
params.push(key + '=' + opt.data[key]);
}
var postData = params.join('&');
if (opt.method.toUpperCase() === 'POST') {
xmlHttp.open(opt.method, opt.url, opt.async);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(postData);
} else if (opt.method.toUpperCase() === 'GET') {
xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
xmlHttp.send(null);
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
opt.success(xmlHttp.responseText);
}
};
}