學習 JavaScript 異步校驗,通常都從最傳統的 XMLHttpRequest 開始。本文以「驗證使用者名稱唯一性」為例,完整走一遍四個步驟,並示範 GET 與 POST 兩種寫法。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>如何使用傳統方法異步驗證用戶名的唯一性</title>
<script type="text/javascript">
function goDemo(pageName){
window.location.href = '<%=basePath%>' + pageName;
}
</script>
</head>
<body>
<center style="margin-top: 10%">
<font style="color: red;font-size: 18pt;font-weight: bold;">如何使用傳統方法異步驗證用戶名的唯一性</font>
</center>
<br>
例子一:<input type="button" value="例子一" onclick="goDemo('demo1.jsp');"/><br><br>
例子二:<input type="button" value="例子二" onclick="goDemo('demo2.jsp');"/><br><br>
兩者的差別在於後端使用的請求方法:「例子一」走 servlet 的 doGet,「例子二」走 doPost。
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>使用的 servlet 中的 doGet 方法</title>
<script type="text/javascript">
function checkUserName(){
var value = document.getElementById("userName").value;
if(value == ""){
document.getElementById("showUserName").innerHTML =
"<font size=\"2\" color=red>用戶名不能為空!!!</font>";
} else {
var xmlHttpRequest = null;
if(window.XMLHttpRequest){
/* 適用於 IE7 以上、Firefox、Chrome、Opera */
xmlHttpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject){
/* 適用於 IE6 及更早版本 */
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// 步驟一:建立物件,此時請求尚未初始化
xmlHttpRequest.onreadystatechange = function(){
// readyState 改變時觸發
if(xmlHttpRequest.readyState == 1){
xmlHttpRequest.send(); // 步驟三:發送請求
}
if(xmlHttpRequest.readyState == 2){
console.log("send() 已執行,請求已送出,但尚未收到回應。");
}
if(xmlHttpRequest.readyState == 3){
console.log("已收到回應標頭,訊息主體尚未接收完畢。");
}
if(xmlHttpRequest.readyState == 4){
// 步驟四:處理伺服器回應
if(xmlHttpRequest.status == 200){
console.log("客戶端已完整接收回應。");
var responseValue = xmlHttpRequest.responseText;
if(responseValue == 1){
document.getElementById("showUserName").innerHTML =
"<font size=\"2\" color=\"red\"> 用戶名已被使用!</font>";
} else if(responseValue == 2){
document.getElementById("showUserName").innerHTML =
"<font size=\"2\" color=\"green\"> 用戶名有效!!!</font>";
}
} else {
document.getElementById("showUserName").innerHTML =
"<font size=\"2\" color=\"red\">請求發送失敗!</font>";
}
}
};
if(xmlHttpRequest.readyState == 0){
// 步驟二:初始化請求。三個參數分別是請求方式、路徑、是否異步
xmlHttpRequest.open("get",
"<%=basePath%>AjaxCheckUserNameServlet?userName=" + value, true);
}
}
}
</script>
</head>
<body>
<center style="margin-top: 10%">
<font style="color: red;font-size: 18pt;font-weight: bold;">使用的 servlet 中的 doGet 方法</font><br><br>
用戶名:<input type="text" id="userName" name="userName" size="27" onblur="checkUserName();">
<font size="2" id="showUserName"> *用戶名必填,具有唯一性。</font>
</center>
</body>
</html>
除了 open 的第一個參數改成 "post",其餘邏輯完全相同:
<%
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<script type="text/javascript">
function checkUserName(){
var value = document.getElementById("userName").value;
if(value == ""){
document.getElementById("showUserName").innerHTML =
"<font size=\"2\" color=red>用戶名不能為空!!!</font>";
} else {
var xmlHttpRequest = null;
if(window.XMLHttpRequest){
xmlHttpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject){
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function(){
if(xmlHttpRequest.readyState == 1){ xmlHttpRequest.send(); }
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var responseValue = xmlHttpRequest.responseText;
if(responseValue == 1){
document.getElementById("showUserName").innerHTML =
"<font size=\"2\" color=\"red\"> 用戶名已被使用!</font>";
} else if(responseValue == 2){
document.getElementById("showUserName").innerHTML =
"<font size=\"2\" color=\"green\"> 用戶名有效!!!</font>";
}
} else {
document.getElementById("showUserName").innerHTML =
"<font size=\"2\" color=\"red\">請求發送失敗!</font>";
}
}
};
if(xmlHttpRequest.readyState == 0){
xmlHttpRequest.open("post",
"<%=basePath%>AjaxCheckUserNameServlet?userName=" + value, true);
}
}
}
</script>
package com.ghj.packagofserlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxCheckUserNameServlet extends HttpServlet {
private static final long serialVersionUID = 6387744976765210524L;
/** 處理 demo1.jsp 的異步驗證 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
// System.out.println(1/0); // 故意製造異常,可測試驗證 status != 200 的分支
String userName = request.getParameter("userName");
System.out.println("處理 demo1.jsp 異步驗證,用戶名為:" + userName);
if ("admin".equals(userName)) {
out.print("1"); // 1 代表用戶名不可用
} else {
out.print("2"); // 2 代表用戶名可用
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
response.setStatus(405);
}
}
/** 處理 demo2.jsp 的異步驗證 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String userName = request.getParameter("userName");
System.out.println("處理 demo2.jsp 異步驗證,用戶名為:" + userName);
if ("admin".equals(userName)) {
out.print("1");
} else {
out.print("2");
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
response.setStatus(405);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns="https://java.sun.com/xml/ns/javaee"
xmlns:web="https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>AjaxCheckUserNameServlet</servlet-name>
<servlet-class>com.ghj.packagofserlet.AjaxCheckUserNameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxCheckUserNameServlet</servlet-name>
<url-pattern>/AjaxCheckUserNameServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
建立 XMLHttpRequest 物件(readyState 0)、呼叫 open 初始化請求、呼叫 send 送出、在 onreadystatechange 中針對 readyState 4 且 status 200 的情況處理回應。GET 把參數接在網址後,POST 則把參數放進 send 的 body。這套流程雖然樸素,卻是理解所有前端異步請求的基礎。