promise实践操作-ajax请求

promise实践操作-ajax请求

代码:

<!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>
    <div class="pro">
        <h4>promise实践操作-ajax请求</h4>
    <button id="btn">点击发送ajax</button>
    </div>
    <script>
        // 获取btn按钮
     const btn = document.querySelector("#btn")
     // 注册点击事件
     btn.addEventListener('click',function () {
    
    
         //promise对象
        const p = new Promise((reslove,reject) => {
    
    
            // 1.创建对象
            const xhr = new XMLHttpRequest()
            // 2.初始化
            xhr.open('GET','https://api.apiopen.top/getJoke')
            // 3.发送
            xhr.send()
            // 4.处理响应结果
            xhr.onreadystatechange = function(){
    
    
                if(xhr.readyState === 4){
    
    
                    // 判断响应状态码
                    if(xhr.status >=200 && xhr.status <300){
    
    
                        // 控制台输出响应体
                        reslove(xhr.response)
                    }
                    // 控制台输出状态码
                    reject(xhr.status)
                }
            }
        })
        // 调用p.then()
        p.then(value => {
    
    
            console.log(value);
        },reason => {
    
    
            console.log(reason);
        })
     })
       
    </script>
</body>
</html>

效果:

在这里插入图片描述

猜你喜欢

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