什么是ajax?
ajax的全名叫做async javascript and xml,即异步的javascript 和 xml
它的实现过程如下:
- 使用 XMLHttpRequest 发请求
- 服务器返回 XML 格式的字符串
- JS 解析 XML,并更新局部页面
注:现在的服务器基本上都是返回json类型的数据了
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)
自己已经封装过一个简单的jQuery了,详见实现一个jQuery的api,接着来为这个jQuery函数本身(函数本事也是一个对象)增加一个ajax的函数
//超简化版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}){名字和传入的参数要相同,位置无需相同
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 规则
因为调用我写的这个jQuery.ajax的api给外人用,根本不知道传入的参数函数叫什么,不看文档你能知道失败的函数叫failFn?并且每个人写的命名不相同。Promise规范不用取名字,标准化了操作
//超简化版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里面传入两个函数,第一个是指success的回调函数,第二个是指fail的回调函数
- then可以通过链式操作透传,下一个then中的函数的参数对应的是上一个中的return值。这样可以多次对结果进行处理
网友评论