美文网首页
get post Promise 封装笔记

get post Promise 封装笔记

作者: 布鲁斯李l | 来源:发表于2020-02-24 14:53 被阅读0次

// 封装一个get请求的方法

            function getJSON(url) {

                return new Promise(function(resolve, reject) {

                    var XHR = new XMLHttpRequest();

                    XHR.open('GET', url, true);

                    XHR.send();

                    XHR.onreadystatechange = function() {

                        if (XHR.readyState == 4) {

                            if (XHR.status == 200) {

                                try {

                                    var response = JSON.parse(XHR.responseText);

                                    resolve(response);

                                } catch (e) {

                                    reject(e);

                                }

                            } else {

                                reject(new Error(XHR.statusText));

                            }

                        }

                    }

                })

            }

      // 封装一个get请求

            function postJSON(url, data) {

    return new Promise( (resolve, reject) => {

        var xhr = new XMLHttpRequest()

        xhr.open("POST", url, true)

        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        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)

                }

            }

        }

        xhr.send(JSON.stringify(data))

    })

}

相关文章

网友评论

      本文标题:get post Promise 封装笔记

      本文链接:https://www.haomeiwen.com/subject/cjdvqhtx.html