每次要用 AJAX 都得寫一大段 try/catch 來建立物件,實在繁瑣。以下從最原始的手寫相容版本談起,再說明如何收攏成可重複使用的函式,最後給出現代的做法。
<html>
<body>
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的瀏覽器不支持 AJAX!");
return false;
}
}
}
}
</script>
<form name="myForm">
用戶:<input type="text" name="username" />
時間:<input type="text" name="time" />
</form>
</body>
</html>
邏輯是:先宣告一個保存 XMLHttpRequest 物件的變數,嘗試用標準寫法 new XMLHttpRequest()(Firefox、Opera、Safari);失敗則嘗試 IE6+ 的 Msxml2.XMLHTTP;再失敗則嘗試 IE5.5+ 的 Microsoft.XMLHTTP;三種都不行,就提示使用者瀏覽器太舊。
不必每次都寫這一大段,把它獨立成一個 js 檔,在需要 AJAX 的頁面引入即可:
function CreateHTTPObject() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest !== 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
調用時建立實例即可:
var xmlHttp = CreateHTTPObject();
if (!xmlHttp) { return; } // 無法建立物件
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function () {
HandleRequest(xmlHttp, "元素ID");
};
xmlHttp.send(null);
注意這裡的順序:必須先 open() 再設定 onreadystatechange,最後才 send()。若把 onreadystatechange 設在 open 之前,某些瀏覽器會漏掉狀態變更的通知。
$(document).ready(function () {
$("#userpass").blur(function () {
var password = $("#userpass").val();
var name = $("#username").val();
var b = false;
if (password === "" || password === null) {
$("#pass").html("<font color='red'>請輸入密碼!</font>");
} else if (!/^[a-zA-Z0-9_]{6,16}$/.test(password)) {
$("#pass").html("<font color='red'>格式不正確!密碼應為 6–16 位數字或字元</font>");
} else {
$.get("LoginAjaxPassword",
{ userpass: encodeURIComponent(password), username: encodeURIComponent(name) },
function (response) {
$("#pass").html(response);
b = (response.indexOf('√') > -1);
});
}
return b;
});
$("#login-submit").click(function () {
var autologin = document.getElementById("autologin").checked;
document.form.action = autologin ? "AutoLogin" : "Login";
document.form.submit();
});
});
這裡有幾處值得留意:encodeURIComponent 只編碼一次就夠了,原本寫成 encodeURI(encodeURI(password)) 會導致二次編碼,後端收到的值可能多出一層 %;另外把提示訊息寫成 <font> 標籤已不建議,改用 class 切換樣式更好:
$("#pass").addClass('is-error').text('請輸入密碼!');
今天的專案完全不需要自己建立 XMLHttpRequest,用內建的 fetch 即可:
fetch('LoginAjaxPassword', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ username: name, userpass: password })
})
.then(function (res) {
if (!res.ok) { throw new Error('HTTP ' + res.status); }
return res.text();
})
.then(function (text) {
document.getElementById('pass').textContent = text;
})
.catch(function (err) {
console.error(err);
});
URLSearchParams 會自動處理編碼,不必手動呼叫 encodeURIComponent;res.ok 檢查 HTTP 狀態;catch 統一捕捉網路錯誤。若回傳的是 JSON,把 res.text() 換成 res.json() 即可。
若環境允許 async/await,語意會更清楚:
async function checkPassword(name, password) {
var res = await fetch('LoginAjaxPassword', {
method: 'POST',
body: new URLSearchParams({ username: name, userpass: password })
});
return res.text();
}
少數情境下原生 XHR 仍有優勢:需要監聽上傳進度(xhr.upload.onprogress)、需要設定 timeout 與 abort、需要同步請求(不建議)時。這時可以封裝一個 Promise 版本:
function request(url, options) {
options = options || {};
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(options.method || 'GET', url, true);
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else {
reject(new Error('HTTP ' + xhr.status));
}
};
xhr.onerror = function () { reject(new Error('網路錯誤')); };
if (options.onprogress) {
xhr.upload.onprogress = options.onprogress;
}
xhr.send(options.body || null);
});
}
結論很明確:新專案用 fetch,需要上傳進度或 abort 控制時用 XHR,而那段三层 try/catch 的相容程式碼,可以留在歷史裡了。