promise 版 ajax 封装

该文章提供了一个使用原生JavaScript封装的AJAX函数,支持Promise,可以进行GET和POST请求。函数对参数进行了验证,确保了请求类型、URL、异步设置和数据参数的正确性。并详细展示了如何处理请求和响应数据。
摘要由CSDN通过智能技术生成

        原生 ajax 封装, 可供参考

function promiseAjax(options) {

        //解构赋值
        const {
            type,   //请求类型
            url,    //地址
            async = true,  //是否异步
            data = {},  //携带参数
            dataType = 'json'   //返回数据格式
        } = options;

        //判断type url async data 的数据类型是否满足要求
        if (type !== 'get' && type !== 'post') {
            throw new Error('请求数据类型错误')
        }

        if (Object.prototype.toString.call(url) !== '[object String]') {
            throw new Error('地址数据类型错误')
        }

        if (Object.prototype.toString.call(async) !== '[object Boolean]') {
            throw new Error('是否异步参数类型错误')
        }

        if (Object.prototype.toString.call(data) !== '[object Object]') {
            throw new Error('携带参数类型错误')
        }

        //拼接地址栏
        let str = '';
        for (let key in data) {
            str += `${key}=${data[key]}`;
        }
        str = str.substring(0, str.length - 1);

        const p = new Promise(resolve => {
            //创建ajax请求
            const xhr = new XMLHttpRequest();

         
        //判断请求方式是get方式还是post请求方式 
        //如果是get请求方式直接在地址栏中拼接携带的参数 如果是post请求方式 在发送请求之前需要先设置一个请求头 然后将携带参数写在send中

        if (type == 'get') {
            xhr.open(type, url + '?' + str)
            xhr.send()
        }
        else {
            xhr.open(type, url);
            //设置一个请求头
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
            //通过send携带参数
            xhr.send(str)
        }

        //等待服务器处理
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = xhr.responseText;
                
                //判断返回数据是否为json字符串格式 如果是的话转换为常规数据格式 
                if (dataType.toLowerCase() === 'json') {    //.toLowerCase()为了不区分大小写
                    data = JSON.parse(res);
                }
                resolve(data)
            }
        }
    })

    return p;                        
}

         测试代码

//测试代码
const p = promiseAjax({
    type: 'get',
    url: 'http://192.168.60.177/php/list.php',
    data: {},
    async: true
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值