雖然 jQuery `$.ajax` 簡潔易用,但理解原生 `XMLHttpRequest` 運作機制有助於除錯與效能調優。本文提供一個完整的「使用者名稱/密碼登入」範例,涵蓋 HTML 表單、原生 JS AJAX 流程、PHP 後端驗證。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX 登入範例</title>
<script src="ajax.js"></script>
</head>
<body>
用戶名:<input id="userName" type="text"><br>
密碼:<input id="passWord" type="password"><br>
<span id="showInputError" style="color:red; font-weight:bold;"></span><br>
<input type="button" value="登入" onclick="doLogin()">
</body>
</html>
var xhr = null;
function doLogin() {
var user = document.getElementById("userName").value;
var pass = document.getElementById("passWord").value;
var errEl = document.getElementById("showInputError");
if (!user) { errEl.innerHTML = "用戶名不能為空"; return; }
xhr = createXHR();
if (!xhr) { alert("瀏覽器不支援 XMLHttpRequest"); return; }
var url = "login.php?userName=" + encodeURIComponent(user) +
"&passWord=" + encodeURIComponent(pass) +
"&t=" + Math.random(); // 防快取
xhr.onreadystatechange = handleResponse;
xhr.open("GET", url, true);
xhr.send(null);
}
function handleResponse() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var resp = xhr.responseText.trim();
if (resp === "yes") {
window.location.href = "main.php"; // 登入成功跳轉
} else {
document.getElementById("showInputError").innerHTML = "用戶名或密碼錯誤";
}
} else {
document.getElementById("showInputError").innerHTML = "伺服器錯誤: " + xhr.status;
}
}
}
function createXHR() {
if (window.XMLHttpRequest) return new XMLHttpRequest(); // 標準瀏覽器
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} // IE6+
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} // IE5
return null;
}
<?php
header("Content-Type: text/plain; charset=utf-8");
$user = $_GET["userName"] ?? "";
$pwd = $_GET["passWord"] ?? "";
$conn = mysqli_connect("localhost", "root", "123456", "my_test");
if (!$conn) { echo "no"; exit; }
mysqli_set_charset($conn, "utf8");
$stmt = $conn->prepare("SELECT 1 FROM Userinfo WHERE userName=? AND pwd=?");
$stmt->bind_param("ss", $user, $pwd);
$stmt->execute();
$stmt->store_result();
echo ($stmt->num_rows > 0) ? "yes" : "no";
$stmt->close();
$conn->close();
?>
// Fetch API (現代瀏覽器)
fetch(`login.php?userName=${encodeURIComponent(user)}&passWord=${encodeURIComponent(pass)}`)
.then(r => r.text())
.then(t => t.trim() === "yes" ? location.href="main.php" : showError("錯誤"));
或使用 `axios`、`jQuery.ajax` 簡化錯誤處理、攔截器、取消請求等進階功能。
原生 AJAX 核心流程:建立 XHR → 註冊 `onreadystatechange` → `open` → `send` → 回調中判斷 `readyState`/`status` → 處理 `responseText`。理解此流程能讓你在任何框架失效或不適用時,快速撰寫輕量級非同步請求。