Promise封装原生Ajax

 function ajaxPromise(method,url,data) {
            return new Promise((resolve, reject) => {
                var xhr = null;
                var method = method || 'GET';
                var data = data || null;
                if (window.XMLHttpRequest) {
                    xhr = new XMLHttpRequest();
                } else {
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }
                xhr.open(method, url, true)

                xhr.onreadystatechange = function () {
                    if (this.readyState === 4) {
                        if (this.status === 200) {
                            resolve(JSON.parse(this.responseText), this)
                        } else {
                            var resJson = { code: this.status, response: this.response }
                            reject(resJson, this)
                        }
                    }
                }

                if(method == 'GET'){
                    xhr.send()
                }else{
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr.send(JSON.stringify(data));
                }
            })

        }

效果展示:

<button id="btn">click</button>

 $('#btn').click(function () {
            ajaxPromise('GET','http://139.9.107.233:5030/data/data.json',null).catch(err => {
                console.log(err);
            }).then(res => {
                console.log(res)
            })
        })

在这里插入图片描述

发布了87 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Hhjian524/article/details/103999853