promise封装ajax
Ajax是我们最常见的异步操作,如何用promise来封装我们的ajax呢?,代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>promise封装ajax</title>
</head>
<body>
<script>
let myAjax = {
post(url,params) {
return new Promise((resolve, reject) =>{
let xhr = new XMLHttpRequest()
xhr.open('post',url)
xhr.send(JSON.stringify(params))
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >=200 && xhr.status<300) {
resolve(xhr.response)
} else {
reject(xhr.status)
}
}
}
})
},
get(url,params) {
return new Promise((resolve, reject) =>{
let xhr = new XMLHttpRequest()
if (Object.keys(params).length>=1) {
url += "?"
}
for (let key in params) {
url += ("key="+params[key] + "&")
}
url = url.substring(0,url.length-1)
xhr.open('get',url)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >=200 && xhr.status<300) {
resolve(xhr.response)
} else {
reject(xhr.status)
}
}
}
})
}
}
myAjax.post("https://api.apiopen.top/getJoke",{id:12})
.then(value => {
console.log(value)
})
</script>
</body>
</html>