Ajax異步驗證登錄或者註冊

首先介紹一個不錯的學習Ajax的中文網站:http://www.w3school.com.cn/ajax/index.aspjavascript

AJAX = 異步 JavaScript 和 XML。詳細介紹見上面的網址便可;html

1:首先介紹一下使用Javascript寫的異步驗證,然而在實際開發過程當中不多用這種的,太過繁瑣,可是依舊寫一個吧!至少懂其原理哦!java

  1.1:第一種方式:先說使用get方法向服務器發送請求的方法吧;jquery

    首先建立一個頁面,如register.jsp,代碼以下所示:ajax

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>註冊的頁面</title>
 8 <script type="text/javascript">
 9     //onblur失去焦點的值
10     
11     //定義一個變量用於存放XMLHttpRequest對象
12     var xmlHttp;
13     function checkIt(){
14         //獲取文本框的值    
15         var account=document.getElementById("account").value;
16         //alert("測試獲取文本框的值:"+account);
17         //先建立XMLHttpRequest對象
18         // code for IE7+, Firefox, Chrome, Opera, Safari
19         if (window.XMLHttpRequest) {
20             xmlHttp = new XMLHttpRequest();
21         } else {// code for IE6, IE5
22             xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
23         }
24         //服務器地址和數據
25         var url="system/usercheck?account="+account;
26         //規定請求的類型、URL 以及是否異步處理請求。
27         xmlHttp.open("GET",url,true);
28         //將請求發送到服務器
29         xmlHttp.send();
30         //回調函數
31         xmlHttp.onreadystatechange=function(){
32             if (xmlHttp.readyState==4 && xmlHttp.status==200){
33                 //給div設置內容
34                 document.getElementById("errorAccount").innerHTML = xmlHttp.responseText;
35             }
36         }
37         //給div設置內容
38         //document.getElementById("errorAccount").innerHTML=account;
39     }
40 </script>
41 </head>
42 <body  bgcolor="#CCFF00">
43 
44 <center>
45     <form action="" method="post">
46         <table>
47             <caption>註冊的頁面</caption>
48             <tr>
49                 <td>帳號:</td>
50                 <td>
51                     <input type="text" name="account" id="account" onblur="checkIt()"/>
52                     <div id="errorAccount" style="color:red;display:inline;"></div>    
53                 </td>
54             </tr>
55             <tr>
56                 <td>密碼:</td>
57                 <td><input type="password" name="password"/></td>
58             </tr>
59             <tr>
60                 <td>姓名:</td>
61                 <td><input type="text" name="username"/></td>
62             </tr>
63             <tr>
64                 <td>性別:</td>
65                 <td><input type="text" name="sex"/></td>
66             </tr>
67             <tr>
68                 <td></td>
69                 <td>
70                     <input type="submit" value="註冊">
71                     <input type="reset" value="重置">
72                 </td>
73             </tr>
74         </table>    
75     </form>
76 </center>
77 </body>
78 </html>

    1.2:實現後臺模擬數據庫登錄的Servlet頁面,源碼以下,類名是UserCheckServlet.java數據庫

 1 package com.bie;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 /** 
13 * @author BieHongLi 
14 * @version 建立時間:2017年3月2日 下午9:06:46 
15 * 
16 */
17 @WebServlet("/system/usercheck")
18 public class UserCheckServlet extends HttpServlet{
19 
20     private static final long serialVersionUID = 1L;
21 
22     @Override
23     protected void doGet(HttpServletRequest request, HttpServletResponse response) 
24             throws ServletException, IOException {
25         this.doPost(request, response);
26     }
27 
28     @Override
29     protected void doPost(HttpServletRequest request, HttpServletResponse response) 
30             throws ServletException, IOException {
31         //設置字符編碼集
32         request.setCharacterEncoding("utf-8");
33         //模擬存在數據庫裏面的帳號
34         String[] arr={"張三","李四","王五","admin","小別"};
35         //獲取前臺傳來的數據
36         String account=request.getParameter("account");
37         
38         //模擬和數據庫裏面的信息匹配
39         boolean mark=false;
40         for(String user:arr){
41             if(user.equals(account)){
42                 mark=true;
43                 break;
44             }
45         }
46         
47         //響應前臺
48         response.setCharacterEncoding("utf-8");
49         response.setContentType("text/html");
50         PrintWriter out=response.getWriter();
51         if(mark){
52             out.println("<font color='red'>該賬號已經存在,請從新輸入!</font>");
53         }else{
54             out.println("<font color='green'>恭喜您,該賬號可使用!</font>");
55         }
56         out.flush();//刷新流
57         out.close();//關閉流
58         
59     }
60     
61     
62 }

 效果以下所示:api


   1.3:第二種方式,使用post方式發送服務器請求;還如上所示,先寫一個jsp頁面,如register2.jsp服務器

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>註冊的頁面</title>
 8 <script type="text/javascript">
 9     //onblur失去焦點的值
10     
11     //定義一個變量用於存放XMLHttpRequest對象
12     var xmlHttp;
13     function checkIt(){
14         //獲取文本框的值    
15         var account=document.getElementById("account").value;
16         //alert("測試獲取文本框的值:"+account);
17         //先建立XMLHttpRequest對象
18         // code for IE7+, Firefox, Chrome, Opera, Safari
19         if (window.XMLHttpRequest) {
20             xmlHttp = new XMLHttpRequest();
21         } else {// code for IE6, IE5
22             xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
23         }
24         //服務器地址和數據
25         var url = "system/usercheck";
26         //規定請求的類型、URL 以及是否異步處理請求。
27         xmlHttp.open("POST",url,true);
28         //向請求添加 HTTP 頭。這個必加,是提交到後臺的方式
29         xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
30         //將請求發送到服務器
31         xmlHttp.send("account="+account);
32         //回調函數
33         xmlHttp.onreadystatechange=function(){
34             if (xmlHttp.readyState==4 && xmlHttp.status==200){
35                 //給div設置內容
36                 document.getElementById("errorAccount").innerHTML = xmlHttp.responseText;
37             }
38         }
39         //給div設置內容
40         //document.getElementById("errorAccount").innerHTML=account;
41     }
42 </script>
43 </head>
44 <body  bgcolor="#CCFF00">
45 
46 <center>
47     <form action="" method="post">
48         <table>
49             <caption>註冊的頁面</caption>
50             <tr>
51                 <td>帳號:</td>
52                 <td>
53                     <input type="text" name="account" id="account" onblur="checkIt()"/>
54                     <div id="errorAccount" style="color:red;display:inline;"></div>    
55                 </td>
56             </tr>
57             <tr>
58                 <td>密碼:</td>
59                 <td><input type="password" name="password"/></td>
60             </tr>
61             <tr>
62                 <td>姓名:</td>
63                 <td><input type="text" name="username"/></td>
64             </tr>
65             <tr>
66                 <td>性別:</td>
67                 <td><input type="text" name="sex"/></td>
68             </tr>
69             <tr>
70                 <td></td>
71                 <td>
72                     <input type="submit" value="註冊">
73                     <input type="reset" value="重置">
74                 </td>
75             </tr>
76         </table>    
77     </form>
78 </center>
79 </body>
80 </html>

   1.4:而後寫後臺,依舊如上所示;如UserCheckServlet.javaapp

 1 package com.bie;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 /** 
13 * @author BieHongLi 
14 * @version 建立時間:2017年3月2日 下午9:06:46 
15 * 
16 */
17 @WebServlet("/system/usercheck")
18 public class UserCheckServlet extends HttpServlet{
19 
20     private static final long serialVersionUID = 1L;
21 
22     @Override
23     protected void doGet(HttpServletRequest request, HttpServletResponse response) 
24             throws ServletException, IOException {
25         this.doPost(request, response);
26     }
27 
28     @Override
29     protected void doPost(HttpServletRequest request, HttpServletResponse response) 
30             throws ServletException, IOException {
31         //設置字符編碼集
32         request.setCharacterEncoding("utf-8");
33         //模擬存在數據庫裏面的帳號
34         String[] arr={"張三","李四","王五","admin","小別"};
35         //獲取前臺傳來的數據
36         String account=request.getParameter("account");
37         
38         //模擬和數據庫裏面的信息匹配
39         boolean mark=false;
40         for(String user:arr){
41             if(user.equals(account)){
42                 mark=true;
43                 break;
44             }
45         }
46         
47         //響應前臺
48         response.setCharacterEncoding("utf-8");
49         response.setContentType("text/html");
50         PrintWriter out=response.getWriter();
51         if(mark){
52             out.println("<font color='red'>該賬號已經存在,請從新輸入!</font>");
53         }else{
54             out.println("<font color='green'>恭喜您,該賬號可使用!</font>");
55         }
56         out.flush();//刷新流
57         out.close();//關閉流
58         
59     }
60     
61     
62 }

 演示效果以下所示:異步


 2:使用jQuery進行異步請求驗證,在開發中最常使用,實際開發過程當中必須會使用的技術;

  推薦一個jQuery在線api的網站(挺不錯的在線查看api,也能夠下載,我用着挺方便的):http://jquery.cuishifeng.cn/ 

  2.1:下面介紹如何使jQuery進行開發,須要注意的是要引入一個jQuery的js,以下:

    <script type="text/javascript" src="js/jquery.min.js"></script>

   2.2:如上,依舊先建立一個register3.jsp頁面,以下代碼所示:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>註冊的頁面</title>
 8 <script type="text/javascript" src="js/jquery.min.js"></script>
 9 <script type="text/javascript">
10     $(document).ready(function(){
11         //給帳號文本框綁定失去焦點的事件
12         $("#account").blur(function(){
13             //alert("測試"+$(this).val());
14             $.ajax({
15                 url:"system/usercheck",//設置服務器地址,即爲servlet配置的url-pattern
16                 type:"post",//提交的方式
17                 data:{account:$(this).val()},//提交到服務器的數據,多個值以逗號分割開{account:$(this).val(),...}
18                 success:function(data){//回調函數,data是返回的數據
19                     $("#errorAccount").html(data);
20                 }
21             });
22         });
23     });
24     
25 </script>
26 </head>
27 <body  bgcolor="#CCFF00">
28 
29 <center>
30     <form action="" method="post">
31         <table>
32             <caption>註冊的頁面</caption>
33             <tr>
34                 <td>帳號:</td>
35                 <td>
36                     <input type="text" name="account" id="account" onblur="checkIt()"/>
37                     <div id="errorAccount" style="color:red;display:inline;"></div>    
38                 </td>
39             </tr>
40             <tr>
41                 <td>密碼:</td>
42                 <td><input type="password" name="password"/></td>
43             </tr>
44             <tr>
45                 <td>姓名:</td>
46                 <td><input type="text" name="username"/></td>
47             </tr>
48             <tr>
49                 <td>性別:</td>
50                 <td><input type="text" name="sex"/></td>
51             </tr>
52             <tr>
53                 <td></td>
54                 <td>
55                     <input type="submit" value="註冊">
56                     <input type="reset" value="重置">
57                 </td>
58             </tr>
59         </table>    
60     </form>
61 </center>
62 </body>
63 </html>

  2.3:後臺servlet代碼依舊如上面的模擬數據庫,代碼以下所示:

 1 package com.bie;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 /** 
13 * @author BieHongLi 
14 * @version 建立時間:2017年3月2日 下午9:06:46 
15 * 
16 */
17 @WebServlet("/system/usercheck")
18 public class UserCheckServlet extends HttpServlet{
19 
20     private static final long serialVersionUID = 1L;
21 
22     @Override
23     protected void doGet(HttpServletRequest request, HttpServletResponse response) 
24             throws ServletException, IOException {
25         this.doPost(request, response);
26     }
27 
28     @Override
29     protected void doPost(HttpServletRequest request, HttpServletResponse response) 
30             throws ServletException, IOException {
31         //設置字符編碼集
32         request.setCharacterEncoding("utf-8");
33         //模擬存在數據庫裏面的帳號
34         String[] arr={"張三","李四","王五","admin","小別"};
35         //獲取前臺傳來的數據
36         String account=request.getParameter("account");
37         
38         //模擬和數據庫裏面的信息匹配
39         boolean mark=false;
40         for(String user:arr){
41             if(user.equals(account)){
42                 mark=true;
43                 break;
44             }
45         }
46         
47         //響應前臺
48         response.setCharacterEncoding("utf-8");
49         response.setContentType("text/html");
50         PrintWriter out=response.getWriter();
51         if(mark){
52             out.println("<font color='red'>該賬號已經存在,請從新輸入!</font>");
53         }else{
54             out.println("<font color='green'>恭喜您,該賬號可使用!</font>");
55         }
56         out.flush();//刷新流
57         out.close();//關閉流
58         
59     }
60     
61     
62 }

演示效果以下所示:


3:若是說還有更加適合進行異步驗證的方法,那麼就是下面這種,直接使用post進行異步驗證,理解其原理,異步驗證so easy!!!

  3.1:首先建立一個頁面register4.jsp,代碼以下所示;

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>註冊的頁面</title>
 8 <script type="text/javascript" src="js/jquery.min.js"></script>
 9 <script type="text/javascript">
10     $(document).ready(function(){
11         //異步驗證
12         $("#account").blur(function(){
13             $.post("system/usercheck2",{account:$(this).val()},
14                 function(data){
15                     if(data=="true"){
16                         //若是已經存在,提示帳號已經被註冊
17                         $("#errorAccount").html("帳號已被註冊,請從新輸入!");
18                     }else{
19                         //這裏能夠註冊的能夠不進行提示,清空便可
20                         $("#errorAccount").html("<font color='green'>帳號能夠註冊喲!</font>");
21                     }
22             },"text");
23         });
24     });
25     
26 </script>
27 </head>
28 <body  bgcolor="#CCFF00">
29 
30 <center>
31     <form action="" method="post">
32         <table>
33             <caption>註冊的頁面</caption>
34             <tr>
35                 <td>帳號:</td>
36                 <td>
37                     <input type="text" name="account" id="account" onblur="checkIt()"/>
38                     <div id="errorAccount" style="color:red;display:inline;"></div>    
39                 </td>
40             </tr>
41             <tr>
42                 <td>密碼:</td>
43                 <td><input type="password" name="password"/></td>
44             </tr>
45             <tr>
46                 <td>姓名:</td>
47                 <td><input type="text" name="username"/></td>
48             </tr>
49             <tr>
50                 <td>性別:</td>
51                 <td><input type="text" name="sex"/></td>
52             </tr>
53             <tr>
54                 <td></td>
55                 <td>
56                     <input type="submit" value="註冊">
57                     <input type="reset" value="重置">
58                 </td>
59             </tr>
60         </table>    
61     </form>
62 </center>
63 </body>
64 </html>

  3.2:此次的servlet後臺處理雖然依舊是模擬數據庫,可是操做卻不同了。須要注意一下;

 1 package com.bie.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 /** 
13 * @author BieHongLi 
14 * @version 建立時間:2017年3月2日 下午9:06:46 
15 * 
16 */
17 @WebServlet("/system/usercheck2")
18 public class UserCheckServlet2 extends HttpServlet{
19 
20     private static final long serialVersionUID = 1L;
21 
22     @Override
23     protected void doGet(HttpServletRequest request, HttpServletResponse response) 
24             throws ServletException, IOException {
25         this.doPost(request, response);
26     }
27 
28     @Override
29     protected void doPost(HttpServletRequest request, HttpServletResponse response) 
30             throws ServletException, IOException {
31         //設置字符編碼集
32         request.setCharacterEncoding("utf-8");
33         //模擬存在數據庫裏面的帳號
34         String[] arr={"張三","李四","王五","admin","小別"};
35         //獲取前臺傳來的數據
36         String account=request.getParameter("account");
37         
38         //模擬和數據庫裏面的信息匹配
39         boolean mark=false;
40         for(String user:arr){
41             if(user.equals(account)){
42                 mark=true;
43                 break;
44             }
45         }
46         
47         //響應前臺
48         response.setCharacterEncoding("utf-8");
49         response.setContentType("text/html");
50         PrintWriter out=response.getWriter();
51         if(mark){
52             out.print("true");
53         }else{
54             out.print("false");
55         }
56         out.flush();//刷新流
57         out.close();//關閉流
58         
59     }
60     
61     
62 }

演示效果以下所示:


 

革命還沒有成功,別同志尚需努力啊!

相關文章
相關標籤/搜索