Ajax案例3-->判断用户名是否被占用
jsp页面--thirdajax.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Insert title here</title> 9 </head> 10 <script type="text/javascript"> 11 function createXMLHttpRequest() { 12 try { 13 return new XMLHttpRequest(); 14 } catch (e) { 15 try { 16 return new ActiveXObject("Msxml2.XMLHTTP"); 17 } catch (e) { 18 try { 19 return new ActiveXObject("Microsoft.XMLHTTP"); 20 } catch (e) { 21 alert("浏览器不兼容"); 22 } 23 } 24 } 25 } 26 27 window.onload = function() { 28 var usernameEle = document.getElementById("username"); 29 usernameEle.onblur = function() {//给文本框的失去焦点事件添加监听器 30 //alert("hello"); 31 32 var xmlHttp = createXMLHttpRequest(); 33 xmlHttp.open("POST", "<c:url value ='/ThirdServlet'/>", true); 34 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 35 xmlHttp.send("username=" + usernameEle.value); 36 37 xmlHttp.onreadystatechange = function() { 38 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { 39 40 var text = xmlHttp.responseText;//得到的是String 41 var flag = eval("(" + text + ")");//eval()执行字符串 42 var error = document.getElementById("errorMsg"); 43 if (flag) { 44 error.innerHTML = "用户名已被注册"; 45 }else{ 46 error.innerHTML=""; 47 } 48 } 49 }; 50 }; 51 }; 52 </script> 53 <body> 54 55 <h1>注册表单</h1> 56 <form action="" method="POST"> 57 姓名<input type="text" id="username" name="username" /><span id="errorMsg"></span><br /> 58 密码<input type="password" /><br /> 59 <input type="submit" value="提交" /> 60 </form> 61 </body> 62 </html>
Servlet-->ThirdServlet.java
1 package ajax; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class ThirdServlet extends HttpServlet { 12 13 private static final long serialVersionUID = 8739665601659312476L; 14 15 public void doPost(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 request.setCharacterEncoding("utf-8"); 19 response.setContentType("text/html;charset=utf-8"); 20 21 String username = request.getParameter("username"); 22 23 /* 24 * 实际开发中需要查询数据库 25 * 这里进行了简化 26 */ 27 if ("lisa".equalsIgnoreCase(username)) { 28 response.getWriter().print(true); 29 } else { 30 response.getWriter().print(false); 31 } 32 33 } 34 35 }
图片展示: