封装底层Ajax


创建Ajax简易步骤:
创建Ajax对象:var xhr=new XMLHttpRequest();
链接服务器:xhr.open('get','a.php',true);
发送请求或数据:xhr.send();
状态值改变时调用函数:xhr.onreadystatechange=fncallback;

封装Ajax:

    function ajax(options){
        
        var url=options.url,
            asy=options.async!==false,
            type=(options.type || 'GET').toUpperCase(),
            data=options.data || null;
            suc=options.success || null,
            err=options.error || null;
            
        xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
        //new XMLHttpRequest()  IE7+, Firefox, Chrome, Opera, Safari
        //new ActiveXObject('Microsoft.XMLHTTP')  ie5、6
        
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                xhr.status==200 ? suc && suc(xhr.responseText) : err && err();
            }
        }
        
        data=(function(data){
            if(data){
                var arr=[];
                for(var i in data){
                    arr.push(encodeURIComponent(i)+'='+encodeURIComponent(data[i]));
                    //encodeURIComponent处理中文等特殊字符编码成%E5%93%88%E5%93%88形式
                }
                return arr.join('&');    //将数组变成字符串:username=name%E5%93%88%E5%93%88&password=123
            }else{
                return data;
            }
        })(data);
        
        if(type=='GET' && data){
            url+= url.indexOf('?')!=-1 ? '&' : '?';
            url+=data+'&t='+Math.random();
        }
        //用一个永远在变的数值Math.random()处理get方式留下的缓存,还可以用时间戳,new Date().getTime()
        //让url成: a.php?username=name%E5%93%88%E5%93%88&password=123&t=0.06531456997618079
        
        xhr.open(type,url,asy);
        
        switch(type){
            case 'POST':
                xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
                data?xhr.send(data):xhr.send();
                break;
            default:
                xhr.send();
        }
    }

使用方法:

    document.onclick=function(){


        ajax({
            type:'post',         //默认:get
            url:'a.php',
            data:{
                username:'name哈哈',
                password:123
            },                      //默认:null
            async:false,        //默认:ture
            success:function(sData){alert(sData)},        //默认为null
            error:function(){alert('出错啦')}                   //默认为null
        });
        
    }

附加:

xhr.readyState属性代码:
0    未初始化的状态。创建了一个XMLHttpRequest对象,尚未初始化
1    连接状态,已经调用了open方法,并且已经准备好发送请求
2    发送状态,已经调用了send方法发出请求,尚未得到响应结果
3    正在接收状态,已经接收了HTTP响应的头部信息,正在接收响应内容
4    已加载状态,此时响应内容已完全被接收

xhr.status常见几种状态:
200——交易成功(OK)
404——没有发现文件、查询或URl(没有找到指定的资源)(Not Found)
500——服务器产生内部错误(Internal Server Error)

xhr.statusText        //返回当前HTTP请求状态
xhr.abort();    //取消异步
xhr.getAllResponseHeaders();    //获取响应头信息-可通过控制台->网络XHR->Response Headers查看
xhr.setRequestHeader();        //设置请求头信息

1、get传送的数据量较小,不能大于2KB。post传送的数据量较大,理论上认为不受限制,实际因服务器或后台限制
2、get安全性低,post安全性较高。
3、从性能上讲post比get更消耗性能,原因是来自网络上的人这么说:“据Yahoo mail team 说: post方法在AJAX 请求下会被拆分成两个: sending header first, then sending data;逆向思维: post的请求如果没有data string,那么性能上应该和get是相同的。” 链接地址:http://cuishen.iteye.com/blog/2019925
~~~简而言之:GET方式传送数据量小,处理效率高,安全性低,会被缓存,而POST反之。

Ajax无注释版下载:

 http://pan.baidu.com/s/1gdh9pyr

原文地址:https://www.cnblogs.com/barrior/p/4090296.html