Promise封装ajax请求
要求:
* 封装一个函数sendAJAX 发送 get ajax请求
* 参数 url
* 返回结果 Promise 对象
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.pro{
width: 300px;
margin: 50px auto;
}
button {
padding: 2px;
font-size: 10px;
border: 1px solid lightblue;
color: #000;
}
</style>
</head>
<body>
<script>
function sendAJAX(url){
return new Promise((resolve,reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET',url)
xhr.send()
xhr.onreadystatechange = function (){
if(xhr.readyState === 4) {
if(xhr.status >=200 && xhr.status <300) {
resolve(xhr.response)
}
reject(xhr.status)
}
}
})
}
sendAJAX('https://api.apiopen.top/getJoke')
.then(value => {
console.log(value.toString());
},reason => {
console.log(reason.toString());
})
</script>
</body>
</html>
效果: