zoukankan      html  css  js  c++  java
  • 手写简易Ajax-结合Promise

    最近面试 还是回到最基础的JS基础入门 自己对着ajax结合Promise又撸了一遍代码

    <!--
     * @Description: 描述
     * @Version: 1.0
     * @Autor: Nanke_南柯
     * @Date: 2020-12-03 05:51:01
     * @LastEditors: Nanke_南柯
     * @LastEditTime: 2020-12-03 06:03:25
    -->
    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>
        <script>
            function ajax(url) {
                return new Promise((resolve, reject) => {
                    const xhr = new XMLHttpRequest;
                    xhr.open('GET', url, true)
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            if (xhr.status === 200) {
                                resolve(xhr.responseText)
                            } else if (xhr.status === 404) {
                                reject(new Error('404 of Founc'))
                            }
                        }
                    }
                    xhr.send(null)
                })
            }
            ajax("./test.json").then(res => {
                console.log('数据获取成功', res);

            }).catch(error => {
                console.log('数据获取失败', error);

            })
        </script>
    </body>

    </html>

     

     成功打印!

    顺便介绍下我vscode的新主题 “Community Material Theme”,这配色简直炒鸡无敌喜欢!!!!!!!!!!!!!!!!

  • 相关阅读:
    PHP双向队列
    [转]数据库查询的3个优化方法
    MySQL性能测试工具 mysqlslap
    PHP各种魔术方法测试
    VBA中级班课时3小结
    VBA中级班课时1小结
    执行cmd并返回程序结果
    Update Dataset data back to Database
    终于会用c#中的delegate(委托)和event(事件)了
    c#: Enqueued event for Queue<T>
  • 原文地址:https://www.cnblogs.com/NanKe-Studying/p/14077470.html
Copyright © 2011-2022 走看看