什么是ajax?
ajax的全名叫做async javascript and xml,即異步的javascript 和 xml
它的實現(xiàn)過程如下:
- 使用 XMLHttpRequest 發(fā)請求
- 服務器返回 XML 格式的字符串
- JS 解析 XML授账,并更新局部頁面
注:現(xiàn)在的服務器基本上都是返回json類型的數(shù)據(jù)了
ajax的使用
// 后端代碼
if(path==='/xxx'){ //path為url中的請求路徑
response.statusCode = 200
response.setHeader('Content-Type', 'text/json;charset=utf-8')
response.write(`
{
"people":{
"name": "海山城",
"age": "25",
"sex": "male"
}
}
`)
response.end()
}
//前端ajax的使用
let request = new XMLHttpRequest()
request.open('GET', '/xxx')
request.send()
request.onreadystatechange = function(){
if(request.readyState === 4){
if(request.status >= 200 && request.status < 300){
let string = request.responseText //服務器返回的JSON類型的字符串
let object = JSON.parse(string ) //通過這個api將JSON類型的字符串轉換成一個對象
}
}
}
封裝一個ajax
封裝一個 jQuery.ajax空执,滿足 jQuery.ajax(url, method, body, success, fail)
自己已經(jīng)封裝過一個簡單的jQuery了,詳見實現(xiàn)一個jQuery的api婴梧,接著來為這個jQuery函數(shù)本身(函數(shù)本事也是一個對象)增加一個ajax的函數(shù)
//超簡化版jQuery
window.jQuery = function(nodeOrSelector){
let nodes = {}
nodes.addClass = function(){}
return nodes
}
window.$ = window.jQuery
window.jQuery.ajax = function(options){
let request = new XMLHttpRequest()
let url = options.url
let method = options.method
let body = options.body
let successFn = options.successFn
let failFn = options.failFn
let headers = options.headers
request.open(method, url)
//header的設置要在open和send之間
for(let key in headers){
request.setRequestHeader(key, headers[key])
}
request.send(body)
request.onreadystatechange = function(){
if(request.readyState === 4){
if(request.status >= 200 && request.status < 300){
successFn.call(undefined, request.responseText)
} else if(request.status >= 400){
failFn.call(undefined, request)
}
}
}
}
$.ajax({
url: 'http://localhost:8000/cors',
method: 'POST',
body: 'name=seaMount&age=25',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'accept': 'text/json'
},
successFn: function(response){
console.log(response)
},
failFn: function(x){
console.log('請求失敗')
console.log(x.responseText)
}
})
注:上面大段用let定義的代碼下梢,看起來挺丑陋的,可以用es6的解構改進
window.jQuery.ajax = function({url, method, body, successFn, failFn, headers}){名字和傳入的參數(shù)要相同塞蹭,位置無需相同
let request = new XMLHttpRequest()
request.open(method, url)
//header的設置要在open和send之間
for(let key in headers){
request.setRequestHeader(key, headers[key])
}
request.send(body)
request.onreadystatechange = function(){
if(request.readyState === 4){
if(request.status >= 200 && request.status < 300){
successFn.call(undefined, request.responseText)
} else if(request.status >= 400){
failFn.call(undefined, request)
}
}
}
}
升級 jQuery.ajax 滿足 Promise 規(guī)則
因為調用我寫的這個jQuery.ajax的api給外人用孽江,根本不知道傳入的參數(shù)函數(shù)叫什么,不看文檔你能知道失敗的函數(shù)叫failFn番电?并且每個人寫的命名不相同岗屏。Promise規(guī)范不用取名字辆琅,標準化了操作
//超簡化版jQuery
window.jQuery = function(nodeOrSelector){
let nodes = {}
nodes.addClass = function(){}
return nodes
}
window.$ = window.jQuery
window.jQuery.ajax = function({url, method, body, headers}){
return new Promise(function(resolve, reject){
let request = new XMLHttpRequest()
request.open(method, url)
//header的設置要在open和send之間
for(let key in headers){
request.setRequestHeader(key, headers[key])
}
request.send(body)
request.onreadystatechange = function(){
if(request.readyState === 4){
if(request.status >= 200 && request.status < 300){
resolve.call(undefined, request.responseText)
} else if(request.status >= 400){
reject.call(undefined, request)
}
}
}
})
}
let promise = $.ajax({
url: 'http://localhost:8000/cors',
method: 'POST',
body: 'name=seaMount&age=25',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'accept': 'text/json'
}
})
promise.then(
function(response){
console.log(response)
},
function(x){
console.log('請求失敗')
console.log(x.responseText)
}
)
- then里面?zhèn)魅雰蓚€函數(shù),第一個是指success的回調函數(shù)这刷,第二個是指fail的回調函數(shù)
- then可以通過鏈式操作透傳婉烟,下一個then中的函數(shù)的參數(shù)對應的是上一個中的return值。這樣可以多次對結果進行處理