【前端开发系列】—— 别说你不会Ajax

 

之前一直都是用封装好的Ajax,所以一直很好奇它是如何使用和实现的。这里正好就进行一下学习,下面是Ajax的一个时间图。

设置触发条件

  这里模拟一个使用场景,就是在用户登陆时,异步的对用户名以及密码进行验证。所以使用onBlur()触发,onBlur函数在输入框焦点遗失时,就会触发。

 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>

创建Ajax的对象

  由于Ajax并不是一个统一的标准,因此各个浏览器有自己的创建方式,因此在创建时,需要进行浏览器的验证,使用如下的验证方法即可。

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

open() onreadystatechante() send()

3.1 open(),这个函数有三个参数,第一个是http的发送方式,常见的有GET和POST,我们这里使用GET,来传送参数;第二个参数是一个url,这个url第一个作用是与后台的servlet进行匹配,第二个作用是传送前台的数据到后台;第三个参数是个bool值,如果为true标识用异步的方式发送请求。

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

3.2 onreadystatechange 指定回调函数,当数据返回时,使用该函数进行处理。我们的处理函数是自己定义的usernameCallback

req.onreadystatechange = usernameCallback;

3.3 send函数用来发送创建好的请求。由于前面的参数已经添加到url后面,因此这里直接使用null作为参数就行了。

req.send(null);

  自己定义的usernameCallback函数,用于把返回的字符串使用DOM方式写入指定的div中。

  在函数返回时,可以使用之前创建好的req对象,调用它的readystate 以及 status属性,4表示XMLHttpRequest对象响应正常结束。200表示HTTP请求获得正确的响应。

  只有这两个条件都满足,才表明异步请求请求成功。

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{
            
        }
    }

通过url与后台的servlet关联

<?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>

简单反馈

    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);
    
    }

另一个验证的servlet采用同样的方式,这里就不再赘述了。下面会贴出所有的代码。

源码暴露

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

运行效果

这里直接判断返回状态,进行样式的改变

成功时的效果!

失败时的效果!

posted @ 2014-09-23 19:18  xingoo  阅读(4683)  评论(1编辑  收藏  举报