zl程序教程

您现在的位置是:首页 >  后端

当前栏目

17.ES6新特性:Promise对象_Ajax实操

ES6对象AJAX 特性 17 Promise 实操
2023-09-27 14:23:04 时间
<!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>
        const getJSON = function (url) {
            const promise = new Promise(function(resolve, reject){
                // 异步操作:网络请求代码

                const handler = function(){
                    if (this.readyState != 4){
                        return;
                    }
                    if(this.status === 200){
                        resolve(this.response)
                    }else{
                        reject(new Error(this.statusText))
                    }
                }
                const client = new XMLHttpRequest(); //ajax
                client.open('GET',url)//请求方式
                client.onreadystatechange = handler;// 接收前后端请求状态
                client.responseType = 'json'
                client.setRequestHeader("Accept", "application/json")
                client.send()
            })
            return promise;
        }

        getJSON("http://iwenwiki.com/api/blueberrypai/getIndexBanner.php")
        .then(function(data){
            console.log(data);
        },function(error){
            console.log(error);
        })





    </script>
</body>
</html>