jQuery ajax异步请求最经常使用的就是当用户注册时,判断用户名是否已经被注册过了。这里给出完整的代码。javascript
ajax_form.jspcss
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>表单自动校验</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <!-- 引入jquery --> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.9.1.js"></script> <script type="text/javascript"> var flag = 0; function lost(){ $("#sp").html(""); var datas = $("#form").serialize();//序列化表单的值,把输入的内容用&符号链接起来name=xxx&paw=xxx,用于ajax向后台发送数据 //这个元素是jquery对象,须要转为dom对象,使用数组下标的方法.也可使用 alert($("#name").val()); $.ajax({ url: "FromServlet", type:"post", data:datas, dataType:"html", beforeSend: function(){ $("#sp").html(""); }, success: function(data, textStatus){ $("#f").html(""); //after的用法:将元素插到指定元素的后面,记住不是包含在里面。这里就是<td></td><span></span>的意思 $("#tt").after("<span id='f'><font fontsize='5' color='red'>"+data+"</font></span>"); }, error:function(XMLHttpRequest, textStatus, errorThrown){ alert(textStatus); } }); }
//表单提交前验证是否合法 function form_serialize(){
if($("#sp").text()!=""){
alert("请从新选择用户名");
return false;
}
return true;html
} </script> </head> <body> <form action="FromServlet" onSubmit="return form_serialize()" id="form"> <table> <tr> <td>用户名:</td> <td id="tt"><input type="text" name="name" onkeyup="lost()" id="name"/> </td> <tr> <td>密 码</td> <td><input type="password" name="password"/></td> </tr> <tr> <td><input type="submit" value="提交" /></td> <td><input type="reset" value="重置"/></td> </tr> </table> </form> </body> </html>
服务端代码:java
FromServlet.javajquery
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); String name = request.getParameter("name"); System.out.println("你输入的是="+name); PrintWriter out = response.getWriter(); //根据用户名判断该用户名是否已经被注册了,若被注册过,则给出提示信息 UserDao userDao = new UserDao(); User user = userDao.getUserByName(name); if(user!=null){ out.println("用户名已经被注册!"); } }
这里只给出了核心方法的代码。ajax
截图:数组