1 Jsp部分: 2
3 <!-- 導入jquery的js外部文件 -->
4 <script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
5 <script>
6 $(function() { 7 //定義全局變量,這里只有一個label,所有用標簽選擇器
8 var lab = $("label"); 9 lab.css("color", "red"); 10 lab.css("font-size", "12px"); 11
12 //點擊任何一個input標簽的button都將執行,本測試只有一個
13 $(":button").click(function() { 14 //獲取指定id的第一個元素內容
15 var name = $("#userName").val(); 16 //執行ajax
17 $.ajax({ 18 //傳輸類型,這里使用Post
19 type: "Post", 20 //傳輸地址,這里是間接路徑,測試路徑在同目錄下
21 url: "search", 22 //傳輸數據,也可以通過問號傳值, 比如 url:"search?name="+name
23 data: {name: name}, 24 //成功執行時
25 success:function(mess) { 26 //消息反饋為 "yes"
27 if(mess=="yes") { 28 //label標簽賦值
29 lab.text("該用戶名已存在!"); 30 }else { 31 lab.text("用戶名可以使用!"); 32 } 33 } 34 }) 35 }) 36
37 }) 38 </script>
39
40 </head>
41 <body>
42
43 <input type="text" id="userName" /><label></label><br/><br/>
44 <input type="button" id="accept" value="驗證用戶名"/>
45
46 </body>
1 Servlet部分: 2
3 @WebServlet("/search") 4 public class searchServlet extends HttpServlet { 5 private static final long serialVersionUID = 1L; 6
7 //get請求方式也傳遞給post處理
8 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 9 doPost(request, response); 10 } 11
12 protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { 13 //避免出現編碼紊亂,統一使用utf-8
14 request.setCharacterEncoding("utf-8"); 15 response.setContentType("text/html; charset=utf-8"); 16 //獲取從跳轉頁面得到的內容
17 String name = request.getParameter("name"); 18 PrintWriter out = response.getWriter(); 19
20 //這里假設驗證 silly 為已存在, 若需要測試實際數據,則可通過jdbc操作從數據庫中查找
21 if(name.equals("silly")) { 22 //給Ajax反饋信息
23 out.print("yes"); 24 }else { 25 out.print("no"); 26 } 27 } 28 }