如何使用promise封装 原生ajax,$.ajax(),以及fetch?(使用promise封装之后,使用封装好的方法请求接口,三种方法都可以好使)


1.如何使用promise封装原生ajax

get

  function getRequest(url) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest()
            xhr.open('GET', url, true)
            xhr.onreadystatechange = function () {
                if(xhr.readyState!=4)return
                if (xhr.readyState === 4 && xhr.status === 200) {
                    resolve(this.responseText, xhr)
                } else {
                    reject(xhr.responseText);
                }
            }
            xhr.send(null)
        })


    }

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 (xhr.readyState != 4) return
                if (xhr.readyState === 4 && xhr.status === 200) {
                    resolve(xhr.responseText)
                } else {
                    reject(xhr.responseText)
                }
            }
            xhr.send(JSON.stringify(data))
        })
    }

2.如何使用promise封装$ajax()

let ajax=function(url, param, type = 'GET'){
    const promise = new Promise(function(resolve, reject){
        $.ajax({
            type: type,
            url: url,
            data: param,
            dataType: 'json',
            success(res) {
                resolve(res)
            },
            error(res) {
                reject('响应错误')
                // reject(res.statusText)
            }
        })
    })
    return promise
}
ajax('http://wh.xhd.cn/api/content/list.jspx',{id: 1}).then(res=>{
    console.log(res)
})

3.fetch的使用

Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局
fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。 这种功能以前是使用 XMLHttpRequest
实现的。Fetch 提供了一个更理想的替代方案,可以很容易地被其他技术使用

1.fetch请求数据

fetch(url, {
  // get 请求可以省略不写 默认的是GET 
  method: 'get'
})
  .then(function(data) {
  return data.text();
}).then(function(data) {
  console.log(data)
});

2.Response对象

fetch的then中返回的不是一个字面量对象,而是一个Response对象的实例,返回的实例可用以下方法,分别处理数据

arrayBuffer() 获取ArrayBuffer格式的promise对象
blob() 获取Bolb格式的promise对象
json() -获取字符串对象
text()获取json的promise对象
formData() 获取formData格式的promise对象

详见fetch文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值