XMLHTTP 物件生命週期短,若每次請求都重複建立與設定,程式碼會變得冗長。封裝後可統一處理物件建立、參數、回呼與錯誤,讓呼叫端更簡潔。
var Ajax = {
getTransport: function () {
return Try.these(
function () { return new ActiveXObject("Msxml2.XMLHTTP"); },
function () { return new ActiveXObject("Microsoft.XMLHTTP"); },
function () { return new XMLHttpRequest(); }
) || false;
}
};在 Prototype 中,Ajax.Request 負責送出請求,Ajax.Updater 則可將 responseText 直接更新到指定容器。使用時需傳入 container、url 與 options,並依需求設定 method、asynchronous 與 postBody。
若使用 POST,Prototype 會將參數編碼為 UTF-8,並設定 application/x-www-form-urlencoded。伺服器端應以相同編碼解析,避免中文亂碼或參數遺失。