ajax实现注册页面动态验证用户名是否已注册,不必提交即可验证。

今天学了一下ajax,感觉很爽啊。ajax真是很强大、

我首先就把我之前一直没解决的问题:如何在前台动态验证用户名是否已注册,而不必提交刷新之后再验证,上代码:

首先,jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> My JSP 'index.jsp' starting page

<%--
--%>


这个其实只是两个文本框,输入用、

下面是js代码。验证用的、

这个没什么可说的,唯一注意的一点就是xmlhttprequest.open("GET", "testajax1?t1="+text1+"&t2="+text2, true);

这里面的testajax1是servlet,注意这个地址需和web.xml保持一致。

接下来是testajax1.java

package com.guang.ajax; 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.guang.sqlhelp.sqlhelp; import java.sql.*; public class testajax1 extends HttpServlet { public testajax1() { super(); } int i=0; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("gbk"); response.setContentType("text/html;charset=gbk"); PrintWriter out = response.getWriter(); //System.out.println("doGet"+i); i++; String t1=request.getParameter("t1"); //System.out.println(t1); //out.println("Hello World"); sqlhelp sp=new sqlhelp(); Connection conn=sp.getconn(); Statement sta=sp.getsta2(conn); String sql="select * from baseinfo where usernum='"+t1+"'"; ResultSet set=sp.getset(sta, sql); int j=0; if(set!=null){ try { set.last(); } catch (SQLException e) { e.printStackTrace(); } try { j=set.getRow(); } catch (SQLException e) { e.printStackTrace(); } if(j==1){ out.println("此学号已被注册,请换一个!!"); } else{ out.println("恭喜您,这个可以注册!"); } out.close(); } } }
那个。上面的也很简单,就是一个取数据的过程,唯一的一个就是验证行数。这个也可以其他的方法。

sqlhelp在这里我就不贴出来了。

你可能感兴趣的:(ajax实现注册页面动态验证用户名是否已注册,不必提交即可验证。)