使用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>
    <title>My JSP 'ajax3.jsp' starting page</title>
    
	<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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript">
//創建異步對象
function createXMLHttpRequest() {
	try {
		return new XMLHttpRequest();//大多數瀏覽器
	} catch (e) {
		try {
			return ActvieXObject("Msxml2.XMLHTTP");//IE6.0
		} catch (e) {
			try {
				return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本	
			} catch (e) {
				alert("您的瀏覽器不支持");
				throw e;
			}
		}
	}
}


window.onload = function() {
	// 獲取文本框,給它的失去焦點事件註冊監聽
	var userEle = document.getElementById("usernameEle");
	userEle.onblur = function() {
		//1.得到異步對象
		var xmlHttp = createXMLHttpRequest();
		//2.打開連接
		//xmlHttp.open("POST", "<c:url value='/ValidateUsernameServlet'/>", true);
		xmlHttp.open("POST", "/Web/ValidateUsernameServlet", true);
		//3.設置請求頭:Content-Type
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		//4.發送請求,給出請求體
		xmlHttp.send("username=" + userEle.value);
		
		//5.給xmlHttp的onreadystatechange事件註冊監聽
		xmlHttp.onreadystatechange = function() {
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {//雙重判斷
				//獲取服務器的響應,判斷是否爲1
				// 是:獲取span,添加內容:“用戶名已被註冊”
				var text = xmlHttp.responseText;
				var span = document.getElementById("errorSpan");
				if(text == "1") {
					//得到span元素
					span.innerHTML = "用戶名已被註冊!";
				} else {
					span.innerHTML = "";
				}
			}
		};
	};
};
</script>
  </head>
  
  <body>
<h1>演示用戶名是否被註冊</h1>
<form action="" method="post">
用戶名:<input type="text" name="username" id="usernameEle"/><span id="errorSpan"></span><br/>
密 碼:<input type="password" name="password"/><br/>
<input type="submit" value="註冊"/>
</form>
  </body>
</html>
ValidateUsernameServlet

package com.java.servlet;

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 ValidateUsernameServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
	
		String username = request.getParameter("username");
		if(username.equals("itachi")) {
			response.getWriter().print("1");
		} else {
			response.getWriter().print("0");
		}
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章