<%@ 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></title> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(function(){ $(":input[name='username']").change(function(){ var val = $(this).val(); val = $.trim(val); if(val != ""){ var url = "${pageContext.request.contextPath}/validatUsername"; var args = {"username":val, "time":new Date()}; $.post(url, args, function(data){ $("#message").html(data); }); } }); }) </script> </head> <body> <!-- 1.导入JQuery库 2.获取name="username"的结点:username 3.1为username添加change响应函数。去除空格且不为空。准备发生Ajax请求。 3.2发送Ajax请求检验username是否可用 3.3在服务端返回一个html片段 3.4在客户端浏览器把其直接添加到#message的html中 --> <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
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub 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='red'>该用户名可以使用</font>"; } response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().print(result); }