美文网首页
使用Promise封装简单Ajax方法

使用Promise封装简单Ajax方法

作者: __越过山丘__ | 来源:发表于2019-01-09 15:51 被阅读0次

readyState:

  • 0: 请求未初始化
  • 1: 服务器连接已建立
  • 2: 请求已接收
  • 3: 请求处理中
  • 4: 请求已完成,且响应已就绪

status:

  • 200: "OK"
  • 404: 未找到页面

GET

function getJSON (url) {
    return new Promise( (resolve, reject) => {
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)

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

        xhr.send()
    })

}

POST

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))
    })
}

相关文章

  • 使用Promise封装简单Ajax方法

    咳咳 一直都很喜欢使用原生的JavaScript,特别是不需要考虑兼容性的场景(虽然少得可怜)。可惜ECMAScr...

  • 使用Promise封装简单Ajax方法

    Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早...

  • 使用Promise封装简单Ajax方法

    readyState: 0: 请求未初始化 1: 服务器连接已建立 2: 请求已接收 3: 请求处理中 4: 请求...

  • fetch

    Fetct fetch:系统基于promise封装的ajax方法 fatch().then().then() 缺点...

  • Promise封装_AJAX

    Promise封装_AJAX 调用格式

  • ES6异步请求

    Promise //Promise其实就是ajax的一个封装方式,简化ajax复杂度//Promise-all适合...

  • 用promise手写Ajax请求

    首先祭上两篇参考文献XHR对象实例所有的配置、属性、方法、回调和不可变值 使用promise手动封装ajax函数...

  • ajax的封装

    前两天,我们研究了Ajax的基本原理和使用方法,那么今天我们在此基础上简单的封装一个ajax。一、ajax怎么封装...

  • promise封装ajax简单实现

    全称AsynchronousJavaScriptXML,异步JavaScript和XML交互一个ajax交互是从X...

  • 封装 jQuery.ajax

    封装一个 jQuery.ajax 升级jQuery.ajax 满足 Promise 规则

网友评论

      本文标题:使用Promise封装简单Ajax方法

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