Promise封装AJAX请求

 

 

 

 

 

复制可用

 //  接口地址:http://poetry.apiopen.top/sentences (随机获取一句诗词)
    
        // 新建一个Promise对象
        const Pro = new Promise((resolve, reject) => {
            // 1.创建对象
            const xhr = new XMLHttpRequest();
    
            // 2.初始化,设置请求方式和接口地址
            xhr.open("GET", "http://api.tianapi.com/film/index?key=74cb68c12016c1e9508bf6d5f981a7be&num=10");
    
            // 3.发送请求
            xhr.send();
    
            // 4.绑定事件,处理响应结果
            xhr.onreadystatechange = function () {
                // 判断
                if (xhr.readyState === 4) {
                    // 判断响应状态码 200~299
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // 获取成功
                        resolve(xhr.response);
                        // console.log(xhr.response);
                    } else {
                        // 获取失败
                        reject(xhr.status);
                        // console.log(xhr.status);
                    }
                }
            }
        });
    
        // 处理状态
        Pro.then((value) => {
            console.log("成功:", value);
        }, (reason) => {
            console.log("失败:", reason);
        })
    </script>

 

去别人博客复制的 也是可以直接用

let myAjax = {
            get() {
                return new Promise((resolve, reject) => {
                    //1,创建Ajax对象
                    let xhr = null;
                    if (window.XMLHttpRequest) {
                        xhr = new XMLHttpRequest();
                    } else { //兼容低版本ie浏览器
                        xhr = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                 //2,建立服务器链接
                    let url = "http://api.tianapi.com/film/index?key=74cb68c12016c1e9508bf6d5f981a7be&num=10";
                    xhr.open("GET", url, true);
                    //3,发送请求
                    xhr.send(null);
                    //4,监听Ajax对象状态变化
                    xhr.onreadystatechange = function() {
                        if (this.readyState == 4 && this.status == 200) {
                            resolve(this.responseText);
                        }
                    }
                });
            }
        }
        myAjax.get().then((res) => {
            let data = JSON.parse(res);
            data.newslist.forEach((v) => {
                console.log(v["title"]);
            });
        }).catch((err) => {
            console.log(err);
        });

 

posted @ 2023-02-11 09:51  罗砂  阅读(74)  评论(0)    收藏  举报