[Series] front-end development - not to mention you will not Ajax

 

Prior has been packaged with Ajax, it has been very curious about how it is used and implemented. Here it just be about learning, the following is a time chart of Ajax.

First, we need to set trigger conditions

  Here we simulate a usage scenario, when a user is logged asynchronous user name and password for authentication. So use onBlur () trigger, onBlur function in the input box lose focus, it will trigger.

 1     <form name="loginForm">
 2         <table>
 3             <tr>
 4                 <td>用戶名:<input type="text" name="username" onBlur="checkUsername()"></td>
 5             </tr>
 6             <tr>
 7                 <td><div id="usernameDiv"></div></td>
 8             </tr>
 9             <tr>
10                 <td>密 码:<input type="password" name="password" onBlur="checkPassword()"></td>
11             </tr>
12             <tr>
13                 <td><div id="passwordDiv"></div></td>
14             </tr>
15         </table>
16     </form>

The second step, we need to create an object of Ajax

  Since Ajax is not a uniform standard, so each browser has its own way to create, so when you create, you need to be verified by the browser, you can use the following authentication methods.

1 if(window.XMLHttpRequest){
2             req = new XMLHttpRequest();
3         }else if(window.ActiveXObject){
4             req = new ActiveXObject("Microsoft.XMLHTTP");
5         }

The third step is to open the function and onreadystatechante function on the timeline above, and send the send function calls.

Open 3.1 () , this function takes three parameters. The first way is to send the http, a common GET and POST, GET we use here, to transmit parameter; the second parameter is a url, the first role of this url the background is matched with the servlet, the second function is to transfer the data back to front; third parameter is a bool value is true if the asynchronous identifier send requests.

req.open("GET",url+"?username="+document.loginForm.username.value,true);

3.2 onreadystatechange specify a callback function, when data is returned using the function process. Our handler is usernameCallback own definition of

req.onreadystatechange = usernameCallback;

3.3 send function for sending the created request. Due to the foregoing parameters have been added to the rear url, so here directly used as a parameter on the list null.

req.send(null);

  usernameCallback own functions defined for the returned string written to the specified manner using the DOM a div.

  When the function returns, before you can use to create a good req object, call its readystate and property status, 4 represents the XMLHttpRequest object in response to the normal end. 200 represents an HTTP request to obtain the correct response.

  Only these two conditions are met, it indicates the asynchronous request request was successful.

function usernameCallback(){
        if(req.readyState == 4){
            if(req.status == 200){
                var str = req.responseText;
                if(str.split("!")[0] == "Success"){
                    document.getElementById("usernameDiv").className = "black";
                }else{
                    document.getElementById("usernameDiv").className = "red";
                }
                document.getElementById("usernameDiv").innerHTML = str;
            }else{
                alert("username failed!");
            }
        }else{
            
        }
    }

  Finally, we need to perform servlet associated with the background by url!

<?xml version="1.0" encoding="GBK"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
      <servlet-name>checkUsername</servlet-name>
    <servlet-class>usernameServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>checkUsername</servlet-name>
      <url-pattern>/checkUsername</url-pattern>
  </servlet-mapping>
  
  <servlet>
      <servlet-name>checkPassword</servlet-name>
    <servlet-class>passwordServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>checkPassword</servlet-name>
    <url-pattern>/checkPassword</url-pattern>
  </servlet-mapping>
</web-app>

  In the servlet, simple to verify

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        String username = request.getParameter("username");
//        System.out.println("username"+username);
        String str = "";
        
        if("xingoo".equals(username)){
            str += "Success!" + username;
        }else{
            str += "failed!" + username;
        }
        
        response.getWriter().write(str);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request,response);
    
    }

Another authentication servlet same way, not repeat them here. Here will be posted all of the code.

Source exposure

Login.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 <style type="text/css">
 7      .red {
 8          color:red;
 9          font-size: 20;
10      }
11      .black {
12          color: black;
13          font-size: 20;
14      }
15 </style>
16 <script language="javascript">
17     function checkUsername(){
18         var url = "checkUsername";
19         if(window.XMLHttpRequest){
20             req = new XMLHttpRequest();
21         }else if(window.ActiveXObject){
22             req = new ActiveXObject("Microsoft.XMLHTTP");
23         }
24         if(req){
25             req.open("GET",url+"?username="+document.loginForm.username.value,true);
26             req.onreadystatechange = usernameCallback;
27             req.send(null);
28         }
29     }
30     function checkPassword(){
31         var url = "checkPassword";
32         if(window.XMLHttpRequest){
33             req = new XMLHttpRequest();
34         }else if(window.ActiveXObject){
35             req = new ActiveXObject("Microsoft.XMLHTTP");
36         }
37         if(req){
38             req.open("GET",url+"?password="+document.loginForm.password.value,true);
39             req.onreadystatechange = passwordCallback;
40             req.send(null);
41         }
42     }
43     function usernameCallback(){
44         if(req.readyState == 4){
45             if(req.status == 200){
46                 var str = req.responseText;
47                 if(str.split("!")[0] == "Success"){
48                     document.getElementById("usernameDiv").className = "black";
49                 }else{
50                     document.getElementById("usernameDiv").className = "red";
51                 }
52                 document.getElementById("usernameDiv").innerHTML = str;
53             }else{
54                 alert("username failed!");
55             }
56         }else{
57             
58         }
59     }
60     function passwordCallback(){
61         if(req.readyState == 4){
62             if(req.status == 200){
63                 var str = req.responseText;
64                 if(str.split("!")[0] == "Success"){
65                     document.getElementById("passwordDiv").className = "black";
66                 }else{
67                     document.getElementById("passwordDiv").className = "red";
68                 }
69                 document.getElementById("passwordDiv").innerHTML = str;
70             }else{
71                 alert("password failed!");
72             }
73         }else{
74             
75         }
76     }
77 </script>
78 </head>
79 <body>
80     <form name="loginForm">
81         <table>
82             <tr>
83                 <td>用戶名:<input type="text" name="username" onBlur="checkUsername()"></td>
84             </tr>
85             <tr>
86                 <td><div id="usernameDiv"></div></td>
87             </tr>
88             <tr>
89                 <td>密 码:<input type="password" name="password" onBlur="checkPassword()"></td>
90             </tr>
91             <tr>
92                 <td><div id="passwordDiv"></div></td>
93             </tr>
94         </table>
95     </form>
96 </body>
97 </html>
View Code

web.xml

<?xml version="1.0" encoding="GBK"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
      <servlet-name>checkUsername</servlet-name>
    <servlet-class>usernameServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>checkUsername</servlet-name>
      <url-pattern>/checkUsername</url-pattern>
  </servlet-mapping>
  
  <servlet>
      <servlet-name>checkPassword</servlet-name>
    <servlet-class>passwordServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>checkPassword</servlet-name>
    <url-pattern>/checkPassword</url-pattern>
  </servlet-mapping>
</web-app>
View Code

usernameServlet.java

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class usernameServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        String username = request.getParameter("username");
//        System.out.println("username"+username);
        String str = "";
        
        if("xingoo".equals(username)){
            str += "Success!" + username;
        }else{
            str += "failed!" + username;
        }
        
        response.getWriter().write(str);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request,response);
    
    }
}
View Code

passwordServlet.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class passwordServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        String password = request.getParameter("password");
//        System.out.println("password"+password);
        String str = "";
        
        if("123".equals(password)){
            str += "Success!" + password;
        }else{
            str += "failed!" + password;
        }
        
        response.getWriter().write(str);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        doGet(request,response);
    
    }
}
View Code

running result

Analyzing the state of direct return Here, styling changes

Effect of success!

Effect of failure!

Reproduced in: https: //my.oschina.net/u/204616/blog/545473

Guess you like

Origin blog.csdn.net/weixin_33711641/article/details/91989893