原生JS封装可兼容的ajax方法以及JQuery的ajax(详细注释)

本文深入探讨了原生JS封装的Ajax方法,确保跨浏览器兼容性,并附有详细注释。同时,对比了jQuery的Ajax实现,提供了一个实践示例。适合希望深入了解Ajax工作原理及高效调用API的前端开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原生JS封装可兼容的ajax方法以及JQuery的ajax(详细注释)

原生封装的ajax,兼容,带详细注释

<script>
    /*
    * type:'get'
    * url: './1.xml'
    * data: {w:1,q:2}  可以不写
    * dataType: 'json' 'xml'  也可以不写  默认值式 json
    * async: true  同步异步   默认式异步
    * cache: 是否支持缓存   只对get起作用 // true
    * success: 请求成功的回调
    * error: 请求失败的回调
    * */

    function ajax(options){
        //初始化数据
        let {
            type='post',
            url,
            data,// 传给后台的参数
            dataType='json', // 限定返回数据的格式
            cache=false, // 默认 不缓存
            async = true,// 初始值 是true 默认式异步
            success,
            error
        } = options ; // 对象的结构赋值 type,url,... 这些都是变量

        //判断data的处理方式  需要放到 xhr.open 的上方
        let str = '';
        if(Object.prototype.toString.call(data) == '[object Object]'){
            //若是对象 则需要用 & 拼接成字符串
            // let str = '';
            for(let k in data){
                if(data.hasOwnProperty(k)){
                    // 如果是 data 的私有属性
                    str += `${k}=${data[k]}&`;
                }
            }
            // str.slice(n,m)  复制 从索引 n  到索引 m (不包含索引m)
            str = str.slice(0,str.length-1);
        }else if(typeof data === 'string'){
            str = data;
        }

        //若  type 是get系列的 ;那么我们需要 把str 拼接到  url  后边
        //用正则去判断 type 是哪个系列的
        let isGet = null;
        let getReg = /get|head|delete/i;
        let postReg = /post|put/i;
        if(getReg.test(type)){
            //就是个get请求
            isGet = true;
        }else if(postReg.test(type)){
            isGet = false;
        };

        //若是个 get请求 ;则需要把url 拼接一下;
        //若 cache 是false;则表示不要走缓存;需要我们拼接一个随机数在url后边
        if(isGet){
            // url = url+`?${str}`;
            if(cache){
                url += `?${str}`;
            }else {
                //不走缓存
                url += `?${str}&t=`+Math.random();
            }
        }


        // 先创建一个原生的ajax对象
        let xhr = new XMLHttpRequest();

        xhr.open(type,url,async);

        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && /^2\d{2}|304/.test(xhr.status)){
                // 代表请求成功   根据dataType 判断返回的数据格式
                switch (dataType.toLowerCase()){
                    // 把参数都转成 小写;防止大小写不同
                    case 'json':
                        // 需要把JSON字符串转成JSON对象,并返回给成功函数
                        try{
                            let json = JSON.parse(xhr.responseText);
                            (success instanceof Function) && success(json);// success 如果是个函数;才去执行
                        }catch (e) {
                            (success instanceof Function) && success(xhr)
                        }

                        break;
                    case 'xml':
                        // 如果要求返回 xml格式; 则直接返回 原生 responseXML
                        (success instanceof Function) && success(xhr.responseXML);
                        break;

                }

            }
            //判断请求失败的情况
            if(/^[45]\d{2}/.test(xhr.status)){
                (error instanceof Function) && error(xhr);
            }
        };
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded;charset=utf-8');
        xhr.send(str)// str --> 1、data 循环拼接出来的   2、用户传进来的字符串
    }

    ajax({
        url:'./1.xml',
        dataType:'xml',
        success: function (data) {
            console.log(data);
        },
        error: function () {

        }
    })
</script> 

jQuery的ajax方法

<script src="js/jquery-3.3.1.js"></script>
<script>
    var xhr = new XMLHttpRequest();
    //get方式的缓存 我们通过url+随机数来解决
    xhr.open('get','./1.xml?t='+Math.random());
    xhr.onreadystatechange = function(){
        console.log(xhr.responseXML);
    };
    // xhr.send();
    $.ajax({
        type:'POST',
        url:'./1.xml',
        data:{q:12,w:13},
        async:true,
        dataType:'XML',// 获取的数据要是一个JSON数据
        cache:true,// 支持使用缓存; 针对get有作用
        success:function (data) {
            console.log(data)
        },
        error:function (res) {
            console.log(res)
        }
    });
    // $.get('https://www.easy-mock.com/mock/5b8f8ee9f9900e4a46af75fc/ajax/userInfo?q=12&w=13',{q:12,w:13},function (data) {
    //     console.log(data);
    // })
</script>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值