AJAX案例二:简单表单验证

案例:如果用户名输入为张三,那么在失去焦点时后面会显示该用户名已被注册,否则显示可以注册!

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function createXMLHttpRequest() {
try {
return new XMLHttpRequest();
} catch (e) {
try {
return ActvieXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return ActvieXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("用的是什么浏览器啊?");
throw e;
}
}
}
}
window.onload = function() {
var btn = document.getElementById("t1");
btn.onblur = function() {
var xmlHttp = createXMLHttpRequest();
xmlHttp.open("POST", "<c:url value='/AServlet'/>", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send("username="+btn.value);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var text = xmlHttp.responseText;
var mesg="";
if(text=="1") mesg="<font color='red'>用户名已被注册!</font>";
if(text=="0") mesg="<font color='blue'>用户名可以注册!</font>";
var spn1 = document.getElementById("spn1");
spn1.innerHTML = mesg;
}
};
};
};
</script>
</head>
<body>
用户名:<input type="text" id="t1"><span id="spn1"></span><br><br>
密 码:<input type="password">
<h1 id="h1"></h1>
</body>
</html>
 import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
if(username.equals("张三")) response.getWriter().print("1");
else response.getWriter().print("0");
}
}

运行截图:

AJAX案例二:简单表单验证

上一篇:Billboard(线段树)


下一篇:HDU1013,1163 ,2035九余数定理 快速幂取模