封装原声ajax

function ajax(data) {

    //data={data:"",datatype:"xml/json",type:"get/post",url:"",asyn:"true/false",success:function(){},failure:function(){}}

    //data:{username;123,password:456}
    //data='username&password=456';

    //第一步 :创建xhr对象
    var xhr = null;
    if(window.XMLHttpRequest) { //标准浏览器
        xhr = new XMLHttpRequest;
    } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    //第二步;准备发送前的一些配置参数
    var type = data.type == 'get' ? 'get' : 'post'; //判断一下方式
    var url = '';
    if(data.url) {
        url = data.url;
        if(type == "get") {
            url += "?" + data.data+"&_t="+new Date().getTime();//处理缓存,获取当前的毫秒数,加一个时间戳
        }
    }
    var flag = data.asyn == 'true' ? 'true' : 'false';
    xhr.open(type, url, flag);
    //第三步;执行发送的动作
    if(type == "get") {
        xhr.send(null);
    } else if(type=='post') {
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send(data.data);
    }

    //第四步 指定回调函数
    xhr.onreadystatechange = function() {
        if(this.readyState == 4) {
            if(this.status == 200) {
                if(typeof data.success == 'function') {
                    var data = data.dataType == 'xml' ? xhr.responseXML : xhr.responseText;
                    data.success(d);
                }
            } else {
                if(typeof data.failure == 'function') {
                    data.failure();
                }
            }
        }
    }
}

//调用方式,使用方法
// var param={
// url:'';
// type;'';
// dataType:'json';
// success:funcion(data){
//
// }
// };
// ajax(param);

原文地址:https://www.cnblogs.com/Abner5/p/6392910.html