码迷,mamicode.com
首页 > Web开发 > 详细

ES6-promise封装AJAX请求

时间:2020-09-04 17:15:15      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:const   状态码   set   reject   对象   响应状态   ISE   request   ==   

<!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>

ES6-promise封装AJAX请求

标签:const   状态码   set   reject   对象   响应状态   ISE   request   ==   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!