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
截圖:數組