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

[ ajax注册验证 ]
1.客户端:JSP

<%@ page language="java" pageEncoding="GBK"%>
<html>
<head>
<title>index.jsp</title>
</head>
<mce:script type="text/javascript"><!--
	var xhr = false;
	function checkUserName(){
		//1.创建XMLHttpRequest对象;
		//IE Browser:
		try{       
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(e){
			try{
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			}catch(e){
				xhr = false;
			}
		}
		if(!xhr&&typeof XMLHttpRequest!="undefined"){
			xhr = new XMLHttpRequest();
		}
		//2.发出请求:
		var url ="serverPort?username="+escape(document.userForm.elements("name").value);
		xhr.open("POST",url,true);
		xhr.onreadystatechange = process;
		xhr.send(null);
	}
	function process(){
		if(xhr.readyState == 4){
			if(xhr.status == 200){
				document.getElementById("userSpan").innerHTML = xhr.responseText;
			}
		}
	}
// --></mce:script>
<body>
	<form action="" method="post" name="userForm">
	<table>
		<caption>用户注册!</caption>
		<tr>
			<td>用户名:</td>
			<td><input type="text" name="name" onblur="checkUserName()"><span id="userSpan">*</span></td>
		</tr>
		<tr>
			<td>密码:</td>
			<td><input type="password" name="password" ></td>
		</tr>
	</table>
	</form>
</body>
</html>

2.服务端:Servlet

package 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;

public class ServerPort extends HttpServlet{
	
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=GBK");
		String userName = request.getParameter("username");
		PrintWriter out = response.getWriter();
		if(userName.trim().length()==0||userName==null){
			out.println("<font color='red'>用户名不能为空!</font>");
		}else if("neyjar".equals(userName)){
			out.println("<font color='red'>用户已存在!</font>");
		}else{
			out.println("<font color='blue'>可以使用此用户名!</font>");
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
}

3.web.xml中配置那个Servlet:

 <servlet>
  	<servlet-name>servletPort</servlet-name>
  	<servlet-class>servlet.ServerPort</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>servletPort</servlet-name>
  	<url-pattern>/serverPort</url-pattern>
  </servlet-mapping>

这就是全部了!
1 楼 kevintang 2010-12-13  
不错,详细说明了每个技术点。现在项目中可能都要从数据库中提取数据了。
这个得根据个人的需要添加了
2 楼 逍遥虎 2010-12-16  
写的不错,但是只是针对ajax刚入门的人来说是一个很好的例子,你还可以解释一下为什么要判断等于4、200。我认为刚入门ajax对这些地方都是比较模糊的。如果只是追求好用还不如用jquery。
3 楼 lao1984wang 2011-04-07  
怎么照着做不对啊 。。。。。。