ajax封装

ajax:
1、创建XMLHttpRequest对象
2、open方法(type,url,async)
3、send方法(params)
4、readyStateChange
get 和 post 区别:
1、get参数拼接到url后边,post参数是放到send方法里的
2、get参数不能识别中文和特殊符号,需要通过encodeURI进行转码,而post支持中文
3、get有缓存,请求需要带上时间戳或者随机数,而post没有缓存
4、get不需要设置请求头,post需要设置请求头

 ajax({
            url: '',
            data: {
                a: 1,
                b: 2
            },
            type: 'get',
            success: function(){},
            error: function(){},
            timeout: 1000,
            complate: function(){}
        })
function ajax(options){
            const {url, data, type, success, error, timeout, complate} = options;
            var xml =  new XMLHttpRequest();
            let method = type.toUpperCase();
            if(method === 'GET'){
                xml.open(method, url + formatData(data), true);
                xml.send();

            }else if(method === 'POST'){
                xml.open(method, url, true);
                xml.send(data);
                xml.setRequestHeader();
            }

            setTimeout(()=>{
                xml.abort();
            }, timeout)

            xml.onreadystatechange = function(){
                if(xml.state === 200 && xml.status === 4){
                    success && success(xml.responseText)
                }else {
                    error && error();
                }
                complate && complate();
            }

        }
 function formatData(obj){
            // '?a=1&b=2&time='+new Date().getTime()   {a:1,b:2}
            let res = '?';
            for(let key in obj){
                res += key + '=' + encodeURI(obj[key]) + '&'
            }
            res += 'time=' + new Date().getTime();
            return res;
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值