註冊或表單輸入時,常需要即時檢查用戶名是否已被使用。若能在使用者輸入完成後立即向後端詢問,就能減少送出表單後才發現錯誤的情況。
在不依賴 jQuery 的情況下,可以先封裝一個通用的 Ajax 請求函式。
function createXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
alert('您的瀏覽器不支援 Ajax');
return null;
}
}
}
function ajaxRequest(url, method, async, callback) {
const xhr = createXHR();
if (!xhr) return;
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.open(method, url, async);
xhr.send();
}當輸入框失去焦點時,可以向後端發送請求,並根據回傳結果更新提示。
function checkUsername() {
const username = document.getElementById('username').value;
ajaxRequest('userServlet?username=' + encodeURIComponent(username), 'POST', true, function (response) {
const message = document.getElementById('usernameMsg');
const input = document.getElementById('username');
if (response === 'yes') {
message.innerHTML = '<font color="red">用戶名已存在</font>';
input.style.backgroundColor = 'red';
} else {
message.innerHTML = '';
input.style.backgroundColor = 'white';
}
});
}後端只需接收 username 參數,判斷是否已存在,並回傳簡單字串即可。
String username = request.getParameter("username");
boolean exists = userList.contains(username);
if (exists) {
response.getWriter().print("yes");
} else {
response.getWriter().print("no");
}實務上可加入防抖處理,避免每次按鍵都發送請求;也可以加上載入狀態、錯誤提示與編碼處理,提升使用者體驗與穩定性。