日期:2014-05-16  浏览次数:20659 次

AJAX简单示例——实现检测用户名是否可用

环境

MyEclipse 8.6 + JDK 1.6 + Tomcat 6.0

 

问题

AJAX简单示例——实现检测用户名是否可用。说明:本文没有涉及数据库,只是一个模拟。

 

解决

CheckNameServlet.java

 

package com.test.servlet;

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 com.test.dao.MemberDao;
import com.test.dto.MemberDto;
import com.test.service.MemberService;
import com.test.service.impl.MemberServiceImpl;

public class CheckNameServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String name = req.getParameter("name");
		
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		//将从客户端得到的字符串进行utf-8编码
		name = java.net.URLDecoder.decode(name,"UTF-8");
		 
		System.out.println(name);
		
		if("123".equals(name)) {
			out.println("用户名:" + name + "已经被使用");
		} else {
			out.println("用户名:" + name + "可以使用");
		}
		
	}
	
}

 

register_ajax.html

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>register.html</title>

		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="this is my page">
		<meta http-equiv="content-type" content="text/html; charset=UTF-8">

		<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
		<script type="text/javascript">
		function check() {
			//获得异步通信对象
			var xmlhttp;
			if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp = new XMLHttpRequest();
			} else {// code for IE6, IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			var name = document.getElementById("name").value;
			xmlhttp.onreadystatechange = function() {//对象的状态切换的时候会调用此方法
				if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ //判断服务器端返回的状态码是不是200
					var info = document.getElementById("info");
					var txt = xmlhttp.responseText;//获得服务器端返回的数据
					info.innerHTML = txt;
				}
			}
			var url = "CheckNameServlet.do?name="+name;
			//两次编码处理中文乱码
			url = encodeURI(url);//把URI字符串采用UTF-8编码格式转化成escape格式的字符串 (空格%20)
			url = encodeURI(url);//将字符串再编码成ISO8859-1的格式
			xmlhttp.open("GET", url, true);
			xmlhttp.send();
		}
</script>
	</head>

	<body>
		<h4>
			用户注册---AJAX验证用户名是否可用
		</h4>
		<form action="register.do" method="post">
			用  户  名:
			<input type="text" id="name" name="username" onblur="check();">
			<br />
			密        码:
			<input type="text" name=&quo