原生ajax
var url = "http://192.168.4.18:8000/"
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
console.log(result)
}
}
回调函数去封装ajax
// 需要记住传参的顺序
function ajax(url,method="get",success) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
success(result)
}
}
}
function ajax({
url,
method="get",
success
}) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
success(result)
}
}
}
jquery-ajax
$.ajax({
url:"http://192.168.4.18:8000/",
type:"get",
dataType:"json",
success:res=>{
console.log(res)
}
})
callback封装jquery-ajax
function http({url,type="get",success}){
$.ajax({
url,
type,
dataType:"json",
success:res=>{
success(rs)
}
})
}
promise封装ajax
将纵向嵌套的ajax,变成横向的了,结构稍微清晰了一点。
function http(url){
return new Promise((resolve,reject)=>{
$.ajax({
url,
type:"get",
success:res=>{
resolve(res)
},
error:err=>{
reject(err);
}
})
})
}