原生JS ajax的封装

1. 封装 get方法

function get(url,data,callBack){

    var xhr = getXHR();

    //处理可选参数

    if(!!data && data instanceof Function){

        callBack = data;

        data = undefined;

    }

    url = url + "?rand=" + new Date().getTime();

    //如果data存在,将data添加给url

    if(!!data){

        url += "&" + serialize(data);

    }

    xhr.open("get",url);

    xhr.send();

    xhr.onreadystatechange = function(){

        if(xhr.readyState === 4){

            if(xhr.status === 200){

                callBack(xhr.responseText);

            }else{

                callBack("请求出现错误:错误提示" + xhr.status + ";错误原因:" + xhr.statusText);

            }

        }

    }

}

2.封装post方法

function post(url,data,callBack){

    var xhr = getXHR();

    //处理data

    if(!!data && data instanceof Function){

        callBack = data;

        data = undefined;

    }

    data = !!data ? serialize(data) : null;


    xhr.open("post",url);


    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");


    xhr.send(data);


    xhr.onreadystatechange = function(){

        if(xhr.readyState === 4){

            if(xhr.status === 200){

                callBack(xhr.responseText);

            }else{

                callBack("请求出现错误:错误提示" + xhr.status + ";错误原因:" + xhr.statusText);

            }

        }

    }

}

3.封装getJson

function getJSON(url,data,callBack){

    if(!!data && data instanceof Function){

        callBack = data;

        data = undefined;

    }

    //处理缓存

    url += "?rand=" + new Date().getTime();

    if(!!data){

        url += "&" + serialize(data);

    }

    var xhr = getXHR();

    xhr.open("GET",url);

    xhr.setRequestHeader("Accept","application/json");

    xhr.responseType = "json";

    xhr.send();

    xhr.onreadystatechange = function(){

        if(xhr.readyState != 4){

            return;

        };

        if(xhr.status == 200){

            callBack(xhr.response);

        }else{

            callBack(new Error("请求出现错误:错误提示" + xhr.status + ";错误原因:" + xhr.statusText));

        }

    }

}


4.完美封装

function ajax(param){

    //处理data

    if(!!param.data){

        param.data = serialize(param.data);

    }

    if(param.type.toLowerCase() === "get"){

        //url要做处理

        param.url += "?rand=" + new Date().getTime();

        if(!!param.data){

            param.url += "&" + param.data;

        }

    }

    var xhr = getXHR();

    xhr.open(param.type,param.url);

    if(param.type.toLowerCase() === "post"){

        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

        xhr.send(param.data || null);

    }else{

        xhr.send();

    }


    xhr.onreadystatechange = function(){

        if(xhr.readyState != 4){

            return;

        };

        if(xhr.status == 200){

            param.success(xhr.response);

        }else{

            if(!!param.error){

                param.error(new Error("请求出现错误:错误提示" + xhr.status + ";错误原因:" + xhr.statusText));

            }

        }

    }

}

//参数序列化

function serialize(obj){

    //"uname=tom&age=19"

    var paramArr = [];//["uname=tom","age=19"];

    //遍历对象

    for(var key in obj){

        //console.log(key);

        paramArr.push(key + "=" + encodeURIComponent(obj[key]));


    }

    //console.log(paramArr);

    return paramArr.join("&");

}

//获取xhr对象

function getXHR(){

    var xhr = null;

    if(!!window.XMLHttpRequest){

        //高版本浏览器

        xhr = new XMLHttpRequest();

    }else{//ie5,6

        xhr = new ActiveXObject("Microsoft.XMLHTTP");

    }

    return xhr;

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容