封装原生Ajax发送请求

(function(window){
    function AjaxTool(){}

    AjaxTool.ajaxRequest = function(params,successCallBack,errCallBack){
        /*
          获取传入的参数
        */

        //请求的类型
        let requestType = params['requestType'] || 'get';
        //请求的路径
        let url = params['url'];
        //传入的数据
        let paramObj = params['paramObj'];
        //延时请求的处理
        let timeout = params['timeout'];


       //创建一个XMLHttpRequest对象,同时需要考虑兼容性问题
        let xhr;
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }

        // 转码,将网络请求进行URI的编码,将请求拿下来之后进行URI的解码,转码之后可以增强Ajax的健壮性
        let codeURI;

       //判断请求方式
        if(requestType.toLowerCase() === 'get'){
            codeURI = encodeURI(url+ '?' +getStrWithObject(paramObj));
            xhr.open('get',codeURI,true);
            xhr.send();
        }else if(requestType.toLowerCase() === 'post'){
            //获取请求体
            codeURI = encodeURI(getStrWithObject(paramObj));
            xhr.open('post',url,true);
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.send(codeURI);
        }

        //监听服务器状态变化
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    successCallBack(xhr);
                    //清除请求定时器
                    clearTimeout(timer);
                }else{
                    errCallBack();
                }
            }
        }

        //处理请求超时问题
        let timer;
        if(timeout > 0){
            timer = setTimeout(function(){
                //取消请求
                xhr.abort();
            },timeout);
        }
    };

    //获取随机数
    function getRandomStr(){
        return Math.random() + (new Date().getTime());
    }

    //将对象转为字符串
    function getStrWithObject(paramsObj){
        let rArr = [];
        // 遍历对象

        for(let key in paramsObj){
            let str = key + "=" +paramsObj[key];
            rArr.push(str);
        }

        //拼接随机数
        rArr.push('random=' + getRandomStr());

        //将数组转换为字符串,以&来做分割
        return rArr.join('&');
    }

    //通过window.AjaxTool就可以访问到AjaxTool方法,这样可以防止全局作用域的污染
    window.AjaxTool = AjaxTool;
})(window);

猜你喜欢

转载自www.cnblogs.com/zhang-jiao/p/10812037.html