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”,这配色简直炒鸡无敌喜欢!!!!!!!!!!!!!!!!

  • 相关阅读:
    计算机组成原理_存储器
    常用CMD命令
    swiper及其父级隐藏之后轮播失效问题
    canvas生成海报
    移动端h5 实现多个音频播放
    vuex的一些学习
    关于H5的一些杂思细想(一)
    vue Error: No PostCSS Config found in
    vue路由传参的三种方式区别(params,query)
    vue-cli+mock.js+axios模拟前后台数据交互
  • 原文地址:https://www.cnblogs.com/NanKe-Studying/p/14077470.html
Copyright © 2011-2022 走看看