es6 promise ajax

promise ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promise ajax</title>

</head>
<body>
<div id="ad">

</div>
<div></div>

<script>

    const p = new Promise((resolve, reject) => {
        //创建对象
        const xhr = new XMLHttpRequest();
        //初始化
        xhr.open("GET", "http://www.example.com:88/ecmas6-11/data.json");
        //发送
        xhr.send();
        //绑定事件
        xhr.onreadystatechange = function () {
            //判断
            if (xhr.readyState === 4) {
                //判断响应码
                if (xhr.status >= 200 && xhr.status < 300) {
                    resolve(xhr.response);
                } else {
                    reject(xhr.status);
                }
            }
        }
    });

    p.then(
        value => {
            console.log(value);
        },
        reason => {
            console.log(reason);
        }
    )


</script>
</body>
</html>
posted @ 2021-06-21 12:09  胡勇健  阅读(29)  评论(0)    收藏  举报