美文网首页
Promise 封装ajax

Promise 封装ajax

作者: 飞鱼_JS | 来源:发表于2017-12-05 10:41 被阅读0次
var getJSON = url=>{
var promise = new Promise((resolve,reject)=>{
    var client = new   XMLHttpRequest()
  client.open("GET",url);
  client.onreadystatechange = hander;
  client.responseType = "json"
  client.setRequesHeader("Accept","application/json");
  client.send()
  function handler(){
    if(this.readyState!==4){
    return ;
}
if(this.status===200){
  resolve(this.response)
}else {
  reject(new Error(this.statusText))
}
}
})
return promise
}

getJSON("/posts.json").then((json)=>{
    console.log(json)
},(error)=>{
  console.log(error)
})

相关文章

网友评论

      本文标题:Promise 封装ajax

      本文链接:https://www.haomeiwen.com/subject/muuqixtx.html