Promise封装ajax请求

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>

      /* 
        *封装一个函数sendAJAX 发送 get ajax请求
        *参数 url
        *返回结果 Promise 对象
        */
       function sendAJAX(url){
    
    
           return new Promise((resolve,reject) => {
    
    
               //1.创建对象
               const xhr = new XMLHttpRequest();
               // 2.初始化
               xhr.open('GET',url)
               // 3.发送
               xhr.send()
               // 4.处理响应状态
               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>

效果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yrfjygb/article/details/113871943