// JS 实现ajax
function ajax(url){
const xhr =new XMLHttpRequest()
xhr.open("GET",url,false)
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
console.log(JSON.parse(xhr.responseText))
}else{
console.log("其他情况")
}
}
}
xhr.send(null)
}
//随便一个请求路径为例
ajax("https://bolt.shaoziketang.com/api/search/keywords?client=3")
//Promise 应用于 ajax
function ajax(url){
const p = new Promise((resolve,reject)=>{
const xhr =new XMLHttpRequest()
xhr.open("GET",url,false)
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
resolve(JSON.parse(xhr.responseText))
}else if(xhr.status===404){
reject(new Error("404 not found")) //抛出错误
}
}
}
xhr.send(null)
})
return p
}
ajax("https://bolt.shaoziketang.com/api/search/keywords?client=3").then(data=>{
console.log(data)
}).catch(ex=>console.error(ex))