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

 

posted @ 2020-12-03 06:13  南柯Dream丶  阅读(211)  评论(0)    收藏  举报