封裝底層Ajax

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   使用   sp   


建立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

 

封裝底層Ajax

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.