HTML代码是这样的
<html>
<head>
<title>Using Ajax for validation</title>
<script type="text/javascript">
var xmlHttp=false;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp) { // 异常,创建对象实例失败
window.alert("不能创建XMLHttpRequest对象实例.");
return false;
}
}
function validate() {
createXMLHttpRequest();
var f = document.form1;
var birthDate = f.birthDate.value;
var url = "servlet/Servlet1?birthDate"+birthDate;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = callback;
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;
alert(mes);
alert(val);
}
}
}
</script>
</head>
<body>
<h1>Ajax Validation Example</h1>
<form name="form1" action="" method="POST">
Birth date: <input type="text" size="10" id="birthDate" onchange="validate();"/>
</form>
</body>
</html>
servlet代码是这样的:
package mypackage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
public class Servlet1 extends HttpServlet
{
private static final String CONTENT_TYPE = "text/html; charset=GBK";
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
boolean passed = validateDate(request.getParameter("birthDate"));//调用方法检验
response.setHeader("Cache-Control","no-cache");
request.setCharacterEncoding("UTF-8");
//设置输出的信息的格式及字符集
response.setContentType("text/xml; charset=UTF-8");
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.close();
}
private boolean validateDate(String date) {
boolean isValid = true;
if(date != null) {
SimpleDateFormat formatter= new SimpleDateFormat("MM/dd/yyyy");
try {
formatter.parse(date);
} catch (ParseException pe) {
System.out.println(pe.toString());
isValid = false;
}
} else {
isValid = false;
}
return isValid;
}
}
运行HTML没有问题,但是输入字符后网页左下角就提示出错了 真的不晓得是怎么回事了.谢谢