0%

AJAX封装

发布于 / 分类: JavaScript / 暂无评论 / 阅读量 514

最后更新于 2018年11月04日

笔记:

//创建XHR对象
function createXHR() {
    if(typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest(); // ie7+ 及现代浏览器
    }else if(typeof ActiveXObject != 'undefined') {
        var versions = ['MSXML2.XMLHttp.6.0','MSXML2.XMLHttp.3.0','MSXML2.XMLHttp']; //ie6及以下版本
        for(var i = 0;i < versions.length;i++){
            try {
                return new ActiveXObject(versions[i]);
            }catch(e) {
                //跳过
            }
        }
    }else {
        throw new Error('您当前的浏览器不支持XHR对象!');
    }
}


//ajax封装 
function ajax(obj){
    var xhr = createXHR();
    obj.url += '?rang=' + Math.random();
    if(obj.method === 'get') {
        obj.url +=obj.url.indexOf('?') == -1 ? '?' +obj.data : '&' + obj.data;   //这里要假设如果不使用'?rang=' + Math.random()的随机数字方法来使ie不读取缓存的话,就要这样判断
    }
    if(obj.async === true){
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                status();
            }
        }
    }
    xhr.open(obj.method,obj.url,obj.async);
    if(obj.method === 'post') {
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xhr.send(obj.data);
    }else {
        xhr.send(null);
    }
    if(obj.async === false) {
        status();
    }
function status() {
        if(xhr.status == 200) {
            obj.soccuss(xhr.responseText);   //数据回调
        }else {
            throw new Error('数据返回出错!错误代码:' + xhr.status + '错误信息:' + xhr.statusText);
        }
}
}

//字符转码
function encod(data){
    var arr = [];
    for(var i in data) {
        arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
    }
    return arr.join('&');
}

//调用代码
addEvent(document,'click',function(){
    ajax({
        method : 'post',
        url : 'demo3.php',
        async : true,
        data : encod({
                name : 'Lee',
                age : 100
        }),
        soccuss : function(text) {
                    alert(text);
                }
    });
})

//兼容添加事件
function addEvent(obj,type,fn) {
    if(obj.addEventListener) {
        obj.addEventListener(type,fn,false);
    }else if(obj.attachEvent){
        obj.attachEvent('on'+type,fn);
    };
}
为博客添加当你滚动后显示返回顶部等快捷键 JS连缀语法
  • 滑动验证
    »
  • weixiao kaixin tushetou jingkong deyi fanu liezui liuhan daku ganga bishi nanguo lihai qian yiwen numu tu yi haixiu se fadai minyan hehe henkaixin huaji biyiyan kuanghan maimeng shui xiaku penqi zhangzui pen aini ye niu laji ok chigua renshi kongbu shuai xiaoxiese touxiao huaixiao jingnu chihuai kaisang xiaoku koubi zhuangbi lianhong kanbujian shafa zhijing xiangjiao dabian yaowan redjing lazhu rizhi duocang chixigua hejiu xixi xiaopen goukun xiaobuchu shenme wusuowei guancha lajing chouyan xiaochi bie zhadanzui zhadanxiao