ES6-promise封装AJAX请求

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- 方法一: -->
<script>
// 接口地址:https://api.apiopen.top/getJoke



// 1.创建对象
const xhr = new XMLHttpRequest();


// 2.初始化
//发 GET类型的请求 给这个接口发请求https://api.apiopen.top/getJoke
// xhr.open("GET","https://api.apiopen.top/getJoke");表示成功
// xhr.open("GET","https://api.apiopen.top/getJoke");
// xhr.open("GET","https://api.apiopen.top/get"); 表示失败
xhr.open("GET","https://api.apiopen.top/get");

// 3.发送
xhr.send();

// 4.绑定事件,处理响应结果
xhr.onreadystatechange=function(){
// 对状态做出一个判断
if(xhr.readyState===4){
// 判断响应状态码 200-300 2系列的响应状态码都为成功
if(xhr.status >= 200 && xhr.status <= 300){
// 表示成功
console.log(xhr.response);
}else{
// 如果失败
console.error(xhr.status);
}

}
}

</script>



<!-- 方法二: -->
<script>
// 接口地址:https://api.apiopen.top/getJoke


const p = new Promise((resolve,reject)=>{
// 1.创建对象
const xhr = new XMLHttpRequest();


// 2.初始化
//发 GET类型的请求 给这个接口发请求https://api.apiopen.top/getJoke
xhr.open("GET","https://api.apiopen.top/getJoke");

// 3.发送
xhr.send();

// 4.绑定事件,处理响应结果
xhr.onreadystatechange=function(){
// 对状态做出一个判断
if(xhr.readyState===4){
// 判断响应状态码 200-300 2系列的响应状态码都为成功
if(xhr.status >= 200 && xhr.status <= 300){
// 表示成功 resolve修改promise的状态
resolve(xhr.response);
}else{
// 如果失败
reject(xhr.status);
}

}
}
})

// 指定回调 结构清晰
p.then(function(value){
// 如果成功打印value
console.log(value);
},function(reason){
console.log(reason);
})
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/weixin2623670713/p/13568477.html