ajax & promise 封装

2021/4/18 18:28:30

本文主要是介绍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>


这篇关于ajax & promise 封装的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程