美文网首页
ajax封装

ajax封装

作者: 嘬烟盒的程序员 | 来源:发表于2017-03-14 18:38 被阅读0次
    //ajax(url,data,type,success,error);
    function ajax(json){
        if(!json.url){
            alert('你是捣乱的');
            return
        }
        json.data=json.data||{};
        json.type=json.type||'get';
        json.time=json.time||'3000';
    
        var time=null;
        if(window.XMLHttpRequest){
            var oAjax=new XMLHttpRequest();
        }else{
            var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
        }
        switch(json.type.toLowerCase()){
            case 'get':
                oAjax.open('GET',json.url+'?'+json2Str(json.data),true);
                break;
            case'post':
                oAjax.open('POST',json.url,true);
                oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                oAjax.send(json2Str(json.data));
                break;
        }
        oAjax.onreadystatechange=function(){
            if(oAjax.readyState==4){
                if(oAjax.status>=200&&oAjax.status<300||oAjax.status==304){
                    json.success&&json.success(oAjax.responseText);//成功后返回的文本
                }else{
                    json.error&&json.error(oAjax.status);
                }
                clearTimeout(timer);
            }
        };
        timer=setTimeout(function(){
            alert('服务器超时了');
            oAjax.onreadystatechange=null;
        },json.time);
    }
    function json2Str(json){
        json.t=Math.random();
        var arr=[];
        for(var name in json){
            arr.push(name+'='+json[name]);
        }
        return arr.join('&')
    }
    

    相关文章

      网友评论

          本文标题:ajax封装

          本文链接:https://www.haomeiwen.com/subject/rznhnttx.html