1 // // 创建对象
2 // const xhr = new XMLHttpRequest();
3 // // 初始化访问方式和地址
4 // xhr.open('get', 'https://api.apiopen.top/getJoke');
5 // //发送访问请求
6 // xhr.send();
7 // //绑定事件接收并处理响应结果
8 // xhr.onreadystatechange = () => {
9 // if(xhr.readyState===4){
10 // //如果返回的状态码在200-300之间
11 // if(xhr.status>=200&&xhr.status<300){
12 // // 表示成功,输入响应结果
13 // console.log(xhr.response)
14 // }else{
15 // // 如果失败,返回错误状态码
16 // console.log(xhr.status)
17 // }
18 // }
19 // }
20
21 // 使用Promise封装XMLHttpRequest
22 const p = new Promise((reslove, reject) => {
23 setTimeout(() => {
24 // 创建对象
25 const xhr = new XMLHttpRequest()
26 // 声明访问方式和访问地址
27 xhr.open('get', 'https://api.apiopen.top/getJoke');
28 // 发送访问请求
29 xhr.send();
30 // 接收响应回调
31 xhr.onreadystatechange = () => {
32 // 与访问地址连接成功
33 if (xhr.readyState === 4) {
34 // 如果返回的状态码在200-300之间,表示成功响应
35 if (xhr.status >= 200 && xhr.status < 300) {
36 // 成功之后使用reslove接收返回的数据体
37 reslove(xhr.response)
38 } else {
39 // 否则使用 reject 接收错误码
40 reject(xhr.status)
41 }
42 }
43 }
44 }, 1000);
45
46 })
47
48 // 声明结果的回调 then支持链式调用
49 p.then(
50 // (value)=>{} 成功的回调
51 (value) => {
52 console.log(value)
53 },
54 // (reason)=>{} 错误的回调
55 (reason) => {
56 console.log(reason)
57 }
58 )