DIV CSS 佈局教程網

自製 Ajax 物件:GET 與 POST 兩種異步傳輸一次封裝
編輯:AJAX基礎知識     

每次寫 Ajax 都要重複一遍「建立物件、判斷瀏覽器、設定回呼」,久了實在煩。與其如此,不如把流程封裝成一個可重複使用的物件。以下這個版本同時支援 GET 與 POST,並把失敗處理也一起包了進去。

核心程式碼

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax Document</title>
<script type="text/javascript">
// 注意:頁面編碼必須統一為 utf-8,才能避免中文參數與中文回值的亂碼問題
function Ajax(prop){
    this.action(prop); // 實例化時即觸發 action 方法
}

Ajax.prototype = {
    createXHR: function(){          // 建立 XMLHttpRequest 物件
        var xhr = false;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xhr;
    },
    action: function(prop){
        var xhr = this.createXHR();
        if (xhr) {
            var url = encodeURI(prop["url"]);   // 對 URL 進行編碼
            if (prop["method"] == "GET" && url && prop["success"]) {   // GET 方法
                xhr.onreadystatechange = function(){
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        prop["success"](xhr);   // 執行回呼函式
                    }
                };
                xhr.open("GET", url, true);
                xhr.send(null);
            }
            else if (prop["method"] == "POST" && url && prop["success"]) {  // POST 方法
                xhr.onreadystatechange = function(){
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        prop["success"](xhr);
                    }
                };
                if (prop["params"]) {
                    url = url.indexOf("?") > -1 ? url + "&" + prop["params"] : url + "?" + prop["params"];
                }
                xhr.open("POST", url, true);
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.send(null);
            }
        }
        else if (!xhr && prop["fail"]) {
            prop["fail"]();
        }
    }
}

function getData(){
    new Ajax({
        url: "test.php",
        method: "POST",
        success: onComplete,
        params: "name=" + escape("沙鋒")   // 傳送前先編碼
    });
}

function onComplete(obj){
    alert(unescape(obj.responseText));   // 接收後再轉碼回來
}
</script>
</head>
<body>
<input type="button" value="Get Data" onclick="getData()"/>
</body>
</html>

參數說明

Ajax 物件接受一個物件字面值作為參數,其中包含下列欄位:

  • method:"GET" 或 "POST"
  • url:伺服器端檔案的路徑
  • success:請求成功時呼叫的回呼函式,會收到 XMLHttpRequest 物件作為參數
  • fail:請求失敗(無法建立 XHR 物件)時呼叫
  • params:使用 POST 送出時的參數字串

幾點值得留意的細節

第一,中文參數必須 encode/decode 成對使用,且頁面編碼要統一為 UTF-8,這是最常見的亂碼來源。第二,範例中的 POST 分支把參數拼在網址後方而非放在 send() 裡,這樣寫雖然能運作,但不符合 POST 的語意,實務上建議改成 xhr.send(prop["params"])。第三,回呼設計成函式傳入,讓呼叫端能各自決定成功後要做什麼,這是封裝能否通用的關鍵。

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