原生js的Ajax请求封装

11 篇文章 0 订阅
const $ = (function() {
    return {
        ajax: function({type,url,data,isAsync,success}) {
            if (!url) {
                console.error('请求地址为空')
                return;
            } 
            //创建 非IE6
            if (window.XMLHttpRequest) {
                var xhr = new XMLHttpRequest();
            } else { //IE6及其以下版本浏览器
                var xhr = new ActiveXObject('Microsoft.XMLHTTP');
            }  
            // 处理data对象
            var queryData = [];
            for (var key in data) {
                // 默认encodeURIComponent
                queryData.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
            }
            queryData = queryData.join('&');

            //连接 和 发送
            if (!type || type == 'GET') {
              // get方式参数要跟在url上
              url = url + '?' + queryData;
              xhr.open("GET", url, isAsync || true);
              xhr.send(null);
            }else if(type=='POST'){
              xhr.open(type,url,isAsync || true);
              //HTTP请求头赋值
              xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
              xhr.send(queryData);
            }

            //接收
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // 有传入success回调就执行
                    success && success(xhr.responseText);
                }
            }
        }
    }
})();

//调用
$.ajax({
    type: 'GET',
    url: 'xxx',
    data: {
        type: 1
    },
    success: function(res) {
        console.log(res);
    }
})
$.ajax({
    type: 'POST',
    url: 'xxx',
    data: {
        type: 1
    },
    success: function(res) {
        console.log(res);
    }
})

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值