ajax & promise 封装

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function ajax() {
            return new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if( this.readyState == 4 ){
                        if( this.status == 200 ){
                            resolve('请求成功')
                        }else{
                            reject('请求失败')
                        }
                    }
                };
                xhr.onerror = function () {
                    reject('接口失败')
                }
                xhr.open('post', 'http://localhost:4010');
                xhr.send();
            })
        }
        ajax().then( function(res){
            console.log(res)
        } )
        .catch( function(res){
            console.log(res)
        } )
    </script>
</body>

</html>
上一篇:day 58 jQuery结束 、 前端框架Bootstrap、 手动搭建一个图书管理系统页面


下一篇:promise和async/await区别