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

Ajax js 使用Ajax检测用户名是否存在
jsp页面:
<script type="text/javascript" language="javascript">
		var xmlHttp = false;
		try {
		    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		    try {
		        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		    } catch (e2) {
		        xmlHttp = false;
		    }
		}
		if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
		    xmlHttp = new XMLHttpRequest();
		}
		
		//检测用户名是否存在
		function callServerCheckUname() {
		    //通过GET方法请求,将请求封装在URL中
		    var uname = document.getElementById("u_name").value;
		    xmlHttp.open("POST", 'CheckUname?u_name='+uname);
		    //设置服务器响应的处理方法
		    xmlHttp.onreadystatechange = updatePageCheckUname;
		    // 发送请求
		    xmlHttp.send(null);
		}
		function updatePageCheckUname() {
		    if (xmlHttp.readyState == 4) {
		        var response = xmlHttp.responseText;
		        if(response >= 1){
		    	    alert("用户名已存在!");
		        }else{
		    	    alert("可注册!");
		        }
		    }
		}
		</script>


web.xml配置文件:
<servlet>
    <servlet-name>CheckUname</servlet-name>
    <servlet-class>servlet.AjaxCheckUname</servlet-class>
  </servlet>
<servlet-mapping>
    <servlet-name>CheckUname</servlet-name>
    <url-pattern>/CheckUname</url-pattern>
  </servlet-mapping>


servlet页面:
public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=GB2312");
		PrintWriter out = response.getWriter();
		try {
			String uname = request.getParameter("u_name");
			RegistDAOImpl regDao = new RegistDAOImpl();
			out.print(regDao.checkUname(uname)) ;
		} catch (Exception e) {
		}
		out.flush();
		out.close();
	}


DAO实现类:
public int checkUname(String uname){
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		int success = 0;
		String sql = "select u_name from u_info where u_name='"+uname+"' or u_mobtel='"+uname+"' or u_email='"+uname+"'";
		try {
			conn = getConnection();
			pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery(sql);
			if(rs.next()){
				success = 1;
			}
			return success;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return success;
	}


紫色头发:http://zisetoufa.iteye.com