AJAX

AJAX

异步的 JavaScript 和 XML

  1. 使用 XMLHttpRequest 发请求
  2. 服务器返回 XML 格式的字符串
  3. JS 解析 XML,并更新局部页面

原生 JS 实现AJAX 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
var request = new XMLHttpRequest()
request.open('GET', '/XXXX')
request.readystatechange = function() {
if(request.readyState === 4) {
console.log('请求完成')
if(request.response.status >= 200 && request.response.status < 300) {
console.log('请求成功')
} else if(request.status >= 400) {
console.log('请求失败')
}
}
}
request.send()

AJAX 的所有功能

  • 客户端的JS发起请求(浏览器上的)
  • 服务端的JS发送响应(Node.js上的)
  1. JS 可以设置任意请求 header
  • 第一部分 request.open(‘get’, ‘/xxx’)
  • 第二部分 request.setRequestHeader(‘content-type’,’x-www-form-urlencoded’)
  • 第四部分 request.send(‘a=1&b=2’)
  1. JS 可以获取任意响应 header
  • 第一部分 request.status / request.statusText
  • 第二部分 request.getResponseHeader() / request.getAllResponseHeaders()
  • 第四部分 request.responseText

模仿 jQuery 封装一个 AJAX

封装代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
window.$ = window.jQuery

window.jQuery.ajax = function({url, method, body, successFn, failFn, headers}){
let request = new XMLHttpRequest()
request.open('method', 'url)
for(let key in headers) {
let value = headers[key]
request.setRequestHeader(value, key)
}
request.readystatechange === function() {
if(request.readyState === 4) {
if(request.response.status >= 200 &&
request.response.status < 300){
successFn.call(undefined, request.responseText)
} else if(request.response.status >= 400) {
failFn.call(undefined, request)
}
}
}
request.send(body)
}

使用封装好的 jQuery.ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function f1(responseText){}
function f2(responseText){}

myButton.addEventListener('click', (e)=>{
$.ajax({
url: '/frank',
method: 'get',
headers: {
'content-type':'application/x-www-form-urlencoded',
'frank': '18'
},
successFn: (x)=>{
f1.call(undefined,x)
f2.call(undefined,x)
},
failFn: (x)=>{
console.log(x)
console.log(x.status)
console.log(x.responseText)
}
})
})

升级jQuery.ajax 满足 Promise 规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
window.$ = window.jQuery

window.jQuery.ajax = function({url, method, body, successFn, failFn, headers}){
return new Promise(function(resolve, reject){
let request = new XMLHttpRequest()
request.open('method', 'url)
for(let key in headers) {
let value = headers[key]
request.setRequestHeader(value, key)
}
request.readystatechange === function() {
if(request.readyState === 4) {
if(request.response.status >= 200 &&
request.response.status < 300){
successFn.call(undefined, request.responseText)
} else if(request.response.status >= 400) {
failFn.call(undefined, request)
}
}
}
request.send(body)
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
myButton.addEventListener('click', (e)=>{
let promise = window.jQuery.ajax({
url: '/xxx',
method: 'get',
headers: {
'content-type':'application/x-www-form-urlencoded',
'frank': '18'
}
})

promise.then(
(text)=>{console.log(text)},
(request)=>{console.log(request)}
)

})