AJAX = Asynchronous JavaScript And XML,非新技術而是整合:
| 方法/屬性 | 說明 |
|---|---|
new XMLHttpRequest() | 現代瀏覽器建立物件 |
open(method, url, async) | 初始化請求,async=true 為異步 |
send(data) | 發送請求,GET 傳 null,POST 傳 key=val&... |
onreadystatechange | 狀態變化回調 |
readyState | 0 未初始化 → 4 完成 |
status | HTTP 狀態碼,200 成功 |
responseText | 文字格式響應 |
open("POST", "login", true)readyState===4 && status===200 處理 responseTextContent-Type: application/x-www-form-urlencodedsend("username=...&password=...")function createXHR() {
if (window.XMLHttpRequest) return new XMLHttpRequest();
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { return new ActiveXObject("Microsoft.XMLHTTP"); }
}
function chkUser() {
var xhr = createXHR();
var u = document.getElementById("username").value;
var p = document.getElementById("password").value;
xhr.open("POST", "login", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("res").innerHTML =
xhr.responseText == '0' ? "登入成功" : "<font color='red'>登入失敗</font>";
}
};
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("username=" + u + "&password=" + p);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String u = req.getParameter("username");
String p = req.getParameter("password");
User user = userService.login(new User(u, p));
resp.getWriter().print(user != null ? 0 : 1);
}
Content-Type,否則後端 getParameter 取不到值。fetch API 或 Axios 封裝,但理解 XHR 為基礎。