function getJSON(url) {
return new Promise((resolve,reject) => {
// 创建一个实例对象
let xhr = new XMLHttpRequest()
// 创建一个新的 http 请求
xhr.open('GET',url,true)
// 发送 http 请求
xhr.send(null)
// 设置状态的监听函数
xhr.onreadystatechange = function() {
if(xhr.readyState !== 4) return // 表示请求完成
// 当请求成功或失败,需要改变 promise 实例的状态
if(xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response) // 请求结果
} else {
reject(new Error(xhr.statusText))
}
}
// 设置错误的监听函数
xhr.onerror = function() {
reject(new Error(xhr.statusText))
}
// 设置相应数据的类型
xhr.responseType = 'json'
})
}
getJSON(url地址).then(data = >{
console.log(data)
}).catch(err =>{
console.log(err)
})
ES6 使用 Promise 封装 ajax
最新推荐文章于 2024-05-31 18:11:33 发布