实现类似 axios.get() 和 axios.post() 的API
const ajax = {
init(type, url, data) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(type, url)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText))
} else {
reject(new Error('请求失败'))
}
}
}
data ? xhr.send(JSON.stringify(data)) : xhr.send()
})
},
get(url) {
return this.init('get', url)
},
post(url, data) {
return this.init('post', url, data)
}
}
const url = '/xxx'
ajax.get(url).then(res => {
console.log(res)
})
网友评论