1. 程式人生 > >ajax註冊頁面非同步驗證

ajax註冊頁面非同步驗證

ajax的原理大家可以看上圖

如何獲得Ajax物件?

XMLHttpRequest沒有標準化,要區分瀏覽器。
  function getXhr(){
   var xhr = null;
   if(window.XMLHttpRequest){
    //非ie瀏覽器
    xhr = new XMLHttpRequest();
   }else{
    //ie瀏覽器
    xhr = new ActiveXObject('MicroSoft.XMLHttp');
   }
   return xhr;
  }

下面我把程式碼貼出來:

1.註冊頁面regist.jsp

<%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8" %>
<html>
	<head>
		<style>
			.tips{
				color:red;
			}
		</style>
		<script type="text/javascript" src="js/my.js"></script>
		<script type="text/javascript">
			function check_username(){
				//獲得ajax物件
				var xhr = getXhr();
				//使用ajax物件發請求
				xhr.open('get',
				'check_username.do?username='
				+$F('username'),true);
				xhr.onreadystatechange=function(){
					//只有readyState等於4,才能獲得
					//伺服器返回的所有資料。
					if(xhr.readyState == 4){
						//判斷伺服器返回的資料是否正確
						if(xhr.status == 200){
							var txt = xhr.responseText;
							$('username_msg').innerHTML = txt;
						}else{
							$('username_msg').innerHTML = '驗證出錯';
						}
					}
				};
				$('username_msg').innerHTML = '正在驗證...';
				xhr.send(null);
			}
			
			function check_number(){
				var xhr = getXhr();
				xhr.open('get',
				'check_number.do?number=' 
				+ $F('number'),true);
				xhr.onreadystatechange=function(){
					if(xhr.readyState == 4){
						var txt = xhr.responseText;
						$('number_msg').innerHTML = txt;
					}
				};
				xhr.send(null);
			}
		</script>
	</head>
	<body style="font-size:30px;font-style:italic;">
		<form action="regist.do" method="post">
			<fieldset>
				<legend>註冊</legend>
				使用者名稱:<input id="username" name="username" 
				onblur="check_username();"/>
				<span class="tips" id="username_msg"></span>
				<br/>
				真實姓名:<input name="name"/><br/>
				驗證碼:<input name="number" id="number" 
				onblur="check_number();"/>
				<span class="tips" id="number_msg"></span>
				<br/>
				<img src="checkcode" 
				onclick="this.src='checkcode?' + Math.random();"/><br/>
				<input type="submit" value="提交"/>
			</fieldset>
		</form>
	</body>
</html>

2.獲得ajax物件my.js

function $(id){
	return document.getElementById(id);
} 

function $F(id){
	return $(id).value;
}

function getXhr() {
	var xhr = null;
	if (window.XMLHttpRequest) {
				//非ie瀏覽器
		xhr = new XMLHttpRequest();
	} else {
				//ie瀏覽器
		xhr = new ActiveXObject("MicroSoft.XMLHttp");
	}
	return xhr;
}

3.servlet驗證頁面ActionServlet.java

package web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ActionServlet extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String uri = request.getRequestURI();
		String action = uri.substring(uri.lastIndexOf("/"),
				uri.lastIndexOf("."));
		if(action.equals("/check_username")){
			
			if(1 == 2){
				throw new ServletException("ģ��һ��ϵͳ�쳣");
			}
			String username =
				request.getParameter("username");
			if(username.equals("tom")){
				out.println("使用者名稱存在");
			}else{
				out.println("使用者名稱未被註冊");
			}
		}else if(action.equals("/check_number")){
			String number1 = 
				request.getParameter("number");
			HttpSession session =
				 request.getSession();
			String number2 = 
				(String)session.getAttribute("number");
			if(number1.equalsIgnoreCase(number2)){
				out.println("驗證碼正確");
			}else{
				out.println("驗證碼錯誤");
			}
		}
		out.close();
	}

}


4.畫驗證碼CheckcodeServlet.java

package web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckcodeServlet extends HttpServlet {
	private int width = 80;
	private int height = 30;
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 繪圖
		 */
			//step1,建立一個記憶體映像物件(畫布)
		BufferedImage image = 
			new BufferedImage(width,height,
					BufferedImage.TYPE_INT_RGB);
			//step2,獲得畫筆
		Graphics g = image.getGraphics();
			//step3,給筆上一個顏色
		Random r = new Random();
		g.setColor(new Color(r.nextInt(255),
				r.nextInt(255),r.nextInt(255)));
			//step4,繪圖,先填充背景 
			g.fillRect(0, 0, width, height);
			//step5,繪圖,給畫筆再設定一個顏色,用來
			//繪圖
			g.setColor(new Color(0,0,0));
			g.setFont(new Font(null,Font.BOLD,20));
			String number = r.nextInt(99999) + "";
			HttpSession session = 
				request.getSession();
			session.setAttribute("number", number);
			g.drawString(number, 10, 22);
		/*
		 * 輸出
		 */
			//step1,設定content-type訊息頭,告訴瀏覽器
			//返回的是一個圖片
			response.setContentType("image/jpeg");
			//step2,獲得一個位元組輸出流
			OutputStream ops = 
				response.getOutputStream();
			//step3,將原始圖片壓縮,然後輸出
			javax.imageio.ImageIO
			.write(image, "jpeg", ops);
			ops.close();
		
	}

}


5.配置檔案web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>web.ActionServlet</servlet-class>
  </servlet>
 <servlet>
    <servlet-name>checkcodeServlet</servlet-name>
    <servlet-class>web.CheckcodeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>checkcodeServlet</servlet-name>
    <url-pattern>/checkcode</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

程式碼我都貼出來了,只是一個簡單的驗證,來測試一下:

ajax是一種用來改善使用者體驗的技術,其實質是利用瀏覽器提供的一個特殊的物件(XMLHttpRequest物件,一般稱之為ajax物件)非同步地(當ajax物件向
 伺服器發請求時,瀏覽器不會銷燬當前頁面,使用者仍然可以對當前頁面做其它的操作)向伺服器傳送請求。 伺服器返回的資料不再是一個完整的新的頁面,而是部分資料,利用這些資料,更新當前頁面。整個過程,頁面無重新整理,不打斷使用者的操作。