DIV CSS 佈局教程網

把 XMLHttpRequest 收進類別:AJAXRequest 初版實作詳解
編輯:AJAX基礎知識     

幫 blog 加上無刷新搜尋與即時驗證檢測之後,我回頭看了一下程式碼,實在太囉嗦:建立 XMLHTTP 物件、判斷瀏覽器、組回呼……這些片段的重複性極高。乾脆把整個請求流程封進一個類別裡,用起來清爽多了,也不用記那麼多細節。檔案已打包附在文末。

想看效果的話,點開側邊欄的日誌搜尋就是無刷新搜尋;另外在閱讀日誌或留言簿的註冊碼欄位有即時檢測——如果不輸入或輸錯驗證碼,輸入框會直接變紅。

類別規格

類別名稱:AJAXRequest

建立方式:var ajaxobj = new AJAXRequest;,若建立失敗會回傳 false。

屬性

  • method:請求方法,字串,POST 或 GET,預設 POST。
  • url:請求的 URL,字串,預設空。
  • async:是否非同步,true 為非同步,false 為同步,預設 true。
  • content:請求內容,方法為 POST 時需設定,預設空。
  • callback:回呼函式,收到回應時呼叫,預設直接回傳。回呼函式有一個參數,即 XMLHttpRequest 物件,定義時寫成 function mycallback(xmlobj)。

方法

send():送出請求,無參數。

使用範例

<script type="text/javascript" src="ajaxrequest.js"></script>
<script type="text/javascript">
var ajaxobj = new AJAXRequest;      // 建立 AJAX 物件
ajaxobj.method = "GET";             // 請求方式設為 GET
ajaxobj.url = "default.asp";        // URL 為 default.asp

// 設定回呼函式,輸出回應內容
ajaxobj.callback = function (xmlobj) {
    document.write(xmlobj.responseText);
}

ajaxobj.send();                     // 送出請求
</script>

完整程式碼

// AJAX 類別
function AJAXRequest() {
    var xmlObj = false;
    var CBfunc, ObjSelf;
    ObjSelf = this;

    try { xmlObj = new XMLHttpRequest; }
    catch (e) {
        try { xmlObj = new ActiveXObject("MSXML2.XMLHTTP"); }
        catch (e2) {
            try { xmlObj = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (e3) { xmlObj = false; }
        }
    }

    if (!xmlObj) return false;

    this.method = "POST";
    this.url;
    this.async = true;
    this.content = "";
    this.callback = function (cbobj) { return; }

    this.send = function () {
        if (!this.method || !this.url || !this.async) return false;

        xmlObj.open(this.method, this.url, this.async);
        if (this.method == "POST")
            xmlObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xmlObj.onreadystatechange = function () {
            if (xmlObj.readyState == 4) {
                if (xmlObj.status == 200) {
                    ObjSelf.callback(xmlObj);
                }
            }
        }

        if (this.method == "POST") xmlObj.send(this.content);
        else xmlObj.send(null);
    }
}

設計上的兩個細節

第一,ObjSelf = this 這一行是關鍵。onreadystatechange 裡的 this 會指向 XMLHTTP 物件而非類別執行個體,因此必須先把外層的 this 存起來,才能在回呼中正確取用 callback。

第二,目前只處理了 status 為 200 的情況,其他狀態碼會靜默失敗。實務上建議在 else 分支加上錯誤通知,否則除錯時會很難定位問題。另外 send 中的 !this.async 判斷也顯得可疑——async 為 false 代表同步請求,本身並不該被視為錯誤,這一行的原意應該是檢查必要參數是否齊全。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved