【网络】仿JQ之AJAX请求

总体思路

  • 兼容IE写法
  • 初始化发送请求open
  • 设置请求头(若有POST请求,GE请求T不用设置)
  • 发送请求
  • 通过onreadystatechange监听readyState

整体代码

var $ = (function(){
    function doAjax(opt){
        var url = opt.url,
            type = opt.type,
            data = opt.data,
            async = opt.async || true,  //异步模式默认开启
            success = opt.success,
            error = function(){
                throw new Error(‘success must be function‘);
            },
            xhr;
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject(‘Mirosoft.XMLHTTP‘);
        }

        xhr.open(type,url,async); //发送HTTP请求
        if(type === ‘POST‘){
            xhr.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘); //POST请求必须设置请求头
            xhr.send(formatData(data));  //发送POST请求
        }else{
            xhr.send(); //GET send的参数为空
        }

        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                if(typeof success === ‘function‘){
                    success(JSON.parse(xhr.responseText));
                }else{
                    error();
                }   
            }
        }
    }

    function formatData(data){
        var list = ‘‘;
        for(var name in data){
            list += name + ‘=‘ + data[name] + ‘&‘;
        }
        list.replace(/&$/, ‘‘);  //去除字符串最后的一位&
        return list;
    }
    return {
        ajax: function(opt){
            doAjax(opt);
        },
        get: function(url,callback){
            doAjax({
                url: url,
                type: ‘GET‘,
                success: callback
            });
        },
        post: function(url,data,callback){
            doAjax({
                url: url,
                type: ‘POST‘,
                data: data,
                success: callback
            });
        }
    }
})();

【网络】仿JQ之AJAX请求

上一篇:webpack初识(webpack是什么?webpack有哪些功能?)


下一篇:Linux防火墙netfilter iptable