1. 程式人生 > 實用技巧 >Ajax 請求

Ajax 請求

1.封裝XMLHttpRequest物件

  // 封裝通用的xhr,相容各個版本
        function createXHR() {
            //判斷瀏覽器是否將XMLHttpRequest作為本地物件實現,針對IE7,Firefox,Opera等瀏覽器
            if (typeof XMLHttpRequest != "undefined") {
                return new XMLHttpRequest();
            } else if (typeof ActiveXObject != "undefined") {
                
//將所有可能出現的ActiveXObject版本放在一個數組中 var xhrArr = ['Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP']; //遍歷建立XMLHttpRequest物件 var len = xhrArr.length; for (var i = 0; i <len; i++) {
try { //建立XMLHttpRequest物件 xhr = new ActiveXObject(xhrArr[i]); //如果建立XMLHttpRequest物件成功,則跳出迴圈 break; } catch (ex) {} } } else { throw new Error("No XHR object available."); } }

2.建立http請求

 xhr.open('get', './ser/se.json', true);   
//xhr.open('post','./ser/se.json',ture);
//如果使用post 就必須適應setRequestHeader()新增http開頭 然後在send()方法中規定希望的資料
//語法:xmlhttp【xhr物件】.setRequestHeader(header,value)
//使用:xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

3.傳送請求

  xhr.send(null);
//post xhr.send({user:"zhangsan",id:6});

4.響應請求

xhr =createXHR()
 //響應XMLHttpRequest物件狀態變化的函式 
        //在我們readystate 屬性發生改變時候
        xhr.onreadystatechange = function() {
            //非同步呼叫成功
        //readyStae 有5給狀態值 分別為0-4
        //0是初始化 表示還沒有呼叫send方法  XMLHttpRequest物件還沒有初始化
        //1是載入完成 send()方法已經執行完成 XMLHttpRequest物件的請求傳送成功
        //2是載入完成 send()方法已經執行完成 XMLHttpRequest物件的請求傳送成功
       //3是解析 正則解析響應的內容 XMLHttpRequest物件讀取伺服器響應的結束
        //4是完成 非同步呼叫完成 響應解析完成 XMLHttpRequest物件讀取服務響應結束
        //當readyState發生改變的時候 會觸發Ajax自帶的事件 onreadystatechang
            if (xhr.readyState=== 4) {
         //status是狀態碼 常見的有200和400 200表示請求成功 100表示客戶端需要繼續傳送請求 404頁面找不到
    //304 表示資源沒有被修改 可以使用瀏覽器快取 也就是表示之前一定請求成功過,而且你請求的資源距離上次請求沒有傳送改變
if ((xhr.status >= 200 && xhr.status <300) || xhr.status === 304) { //獲得伺服器返回的資料 //eval 轉換為js來使用 date = eval("("+xhr.responseText+")"); console.log(date.slider);      
} } };

5.