var obj = {
    type:"post",
    url:"XXX",
    dataType:"json",
    data:{
        age:"18",
        name:"Bob"
    },
    success:function(){};
};
function myAjax(obj){
    var default = {
        type:"get",
        url:"#",
        dataType:"json",
        data:{},
        ays:true,
        success:function(result){console.log(result);}
    };
    //obj中的属性,覆盖到defaults中的属性
    //1、如果有一些属性只存在obj中,会给defaults中增加属性
    //2、如果有一些属性同时存在在obj何defaults中,会将defaults中的默认值覆盖
    //3、如果有一些属性只在defaults中存在,在obj中不存在,此时defaults中将保留预定义值
    for(var key in obj){
        defaults[key] = obj[key];
    }
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else {
        xhr = new ActiveXObject("Microsoft.XNLHTTP");
    }
    //得到params
    var params = "";
    for(var attr in defaults.data){
        params += attr + "=" defaults.data[attr] + "&"
    }
    if(params){
        params = params.substring(0,params.length,-1);
    }
    if(defaults.type == "get"){
        defaults.url += "?" + params;
    }
    xhr.open(defaults.type,defaults.url,defaults.ays);
    if(defaults.type == "get")
    {
        xhr.send(null);
    }else if(defaults.type == "post"){
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send(params);
    }

    if(defaults.ays){
        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    if(defaults.dataType == "json"){
                        result = xhr.responseText;
                        result = JSON.parse(result);
                    }
                    else if(defaults.dataType == "xml"){
                        result = xhr.responseXML;
                    }else{
                        result = xhr.responseText;
                    }
                    defaults.success(result;)
                }
            }
        }
    }
    else{
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                if(defaults.dataType == "json"){
                    result = xhr.responseText;
                    result = JSON.parse(result);
                }
                else if(defaults.dataType == "xml"){
                    result = xhr.responseXML;
                }else{
                    result = xhr.responseText;
                }
                defaults.success(result;)
            }
        }
    }

}

最后推荐一个公众号,一枚IT技术人成长路上关于生活和职场的思考,欢迎书友们前来交流和分享心得

ajax封装优化实现_其他