Ajax验证用户名是否可用
用到的插件:
jquery-1.9.1.js
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="${pageContext.request.contextPath }/html/scripts/jquery-1.9.1.js"></script> <script type="text/javascript"> $(function(){ //选择name="username"的DOM对象 $(":input[name='username']").change(function(){ var val = $(this).val();//获取当前对象的对象值 val = $.trim(val);//去掉字符串首尾空格 //发送Ajax请求 if(val != ""){ var url = "${pageContext.request.contextPath }/valiateUserName"; var args = {"username":val,"time":new Date()}; $.post(url,args,function(data){ $("#message").html(data); }) } }) }) </script> </head> <body> <form action="" method="post"> UserName:<input type="text" name="username"/> <br> <div id="message"></div> <br> <input type="submit" value="Submit"/> </form> </body> </html>
servlet
import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class valiateUserName */ @WebServlet("/valiateUserName") public class valiateUserName extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> usernames =Arrays.asList("AAA","BBB","CCC"); String username = request.getParameter("username"); String result = null; if(usernames.contains(username)) { result = "<font color='red'>该用户名已经被使用</font>"; }else { result = "<font color='green'>该用户可以使用</font>"; } response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(result);//response.getWriter().print(),不仅可以打印输出文本格式的(包括html标签) } }
结果截图:
可以进一步连接数据库来操作,这里我就不写了。