例子来源:《Ajax 基础教程》 金灵 等译 这本书非常不错
validation.html
ValidationServlet.java
validation.html
<html>
<head>
<title>Using Ajax for validation</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function validate() {
createXMLHttpRequest();
var date = document.getElementById("birthDate");
var url = "ValidationServlet?birthDate=" + escape(date.value);
xmlHttp.onreadystatechange = callback;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function callback() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
var mes = xmlHttp.responseXML.getElementsByTagName("message")[0].firstChild.data;
var val = xmlHttp.responseXML.getElementsByTagName("passed")[0].firstChild.data;
setMessage(mes, val);
}
}
}
function setMessage(message, isValid) {
var messageArea = document.getElementById("dateMessage");
var fontColor = "red";
if (isValid == "true") {
fontColor = "gree";
}
messageArea.innerHTML = "<font color=" + fontColor + ">" + message + " </font>";
}
</script>
</head>
<body>
<h1>Ajax Validation Example</h1>
Birth date: <input type="text" size="10" id="birthDate" onchange="validate();" />
<div id="dateMessage"></div>
</body>
</html>
ValidationServlet.java
package ajaxbook.chap4;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidationServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
boolean passed = validateDate(request.getParameter("birthDate"));
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
String message = "You have entered an invalid date.";
if (passed) {
message = "You have entered a valid date.";
}
out.println("<response>");
out.println("<passed>" + Boolean.toString(passed) + "</passed>");
out.println("<message>" + message + "</message>");
out.println("</response>");
out.println();
out.close();
}
private boolean validateDate(String date) {
boolean isValid = true;
if (date != null) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
try {
formatter.parse(date);
} catch (ParseException e) {
System.out.println(e.toString());
isValid = false;
}
} else {
isValid = false;
}
return isValid;
}
}