Struts2 Ajax校驗

Ajax(Asynchronous javascript and xml):異步刷新技術

 技術組成:
  CSS + xml +JavaScript +DOMjavascript

 Ajax核心對象: XMLHttpRequest
 應用場景:實現頁面的局部刷新
 html

 

Ajax:異步刷新技術java

XMLHttpRequest的經常使用方法ajax

 

XMLHttpRequest的經常使用屬性:瀏覽器

readystate:XMLHttpRequest的狀態信息服務器

onreadystatechange:設置回調函數app

status:返回當前請求的Http狀態碼dom

responseText:以文本形式獲取相應之異步

responseXML:以XML形式獲取響應值,而且解析成DOM對象返回jsp

statusText:返回當前請求的響應行狀態

 

使用Ajax發送GET請求及處理響應

在index.jsp 驗證用戶是否存在

步驟:

1.建立XMLHttpRequest對象

2.設置回調函數

3.初始化XMLHttpRequest對象

4.發送請求

複製代碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>My JSP 'index.jsp' starting page</title>
    <script type="text/javascript">
    
      //給文本框註冊一個失去焦點事件
    window.onload=function(){
        var dom=document.getElementById("txtName");
          dom.onblur=function(){
             myajax();
          };
    
    };
      
    
    function myajax(){
    
       //01.定製出 xhr對象
       var xhr;
       //02.能力檢測
       if(window.XMLHttpRequest){
           //非IE瀏覽器   
          xhr=new XMLHttpRequest();
       }else{
          //IE內核
          xhr=new ActiveXObject("Microsoft.XMLHttp");
       }
        var dom=document.getElementById("txtName");
        var myspan=document.getElementById("msg");
        var myval=dom.value;
       //03.構建請求地址
       //xhr.open("請求類型","請求地址","是否異步");
       xhr.open("get","<%=path%>/servlet/CheckUserServlet?uname="+myval,true);

       //04.設置回調函數     響應回來的數據
       xhr.onreadystatechange=function(){
         //什麼
         if(xhr.readyState==4&&xhr.status==200){
            //獲取響應數據
            var data=xhr.responseText;
            if(data=='OK'){
                
                 myspan.innerText="用戶名已經被註冊";
            }else{
            
                 myspan.innerText="用戶名能夠註冊";
            }
         }
       };
       
       
       //05.用send真正的發送請求
       xhr.send(null);

       }
       
    </script>
  </head>
  
  <body>
    <input type="text" name="txtName" id="txtName"/> <span id="msg"></span><br/>
    <input type="password" name="txtPwd"/>
  </body>
</html>
複製代碼

經過XMLHttpRequest的返回值判斷當前瀏覽器建立XMLHttpRequest對象的方式。若是爲true,說明是其餘瀏覽器;若是爲false,說明是ie瀏覽器,需使用new ActiveXObject("Microsoft.XMLHttp")對象

經過XMLHttpRequest對象的onreadystatechange屬性設置回調函數,用於當請求成功後接收服務器端返回的數據

經過XMLHttpRequest對象的open()方法,傳入參數完成初始化XMLHttpRequest對象的工做。第一個參數爲Http請求方式,選擇發送Httpget 請求,所以參數爲get。第二個參數爲要發送的url請求路徑,將要發送的數據附加到url路徑後面

調用XMLHttpRequest對象的send()方法,參數爲要發送到服務器端的數據,由於採用"get"方式請求時,參數已經附加到url路徑後,因此直接設置爲null。若是send()方法不設值,在不一樣的瀏覽器下可能存在不兼容問題。

servlet

複製代碼
package cn.servlet;

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 CheckUserServlet extends HttpServlet {

    /**
     * hh
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    /**
     *hh
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String uname=request.getParameter("uname");
        if(uname.equals("admin")){
            response.getWriter().write("OK");
        }else{
            response.getWriter().write("NO");
        }
    }

}
複製代碼

效果:

若是用戶名不等於admin,顯示用戶能夠註冊;等於admin,顯示用戶已經被註冊

使用Ajax發送post請求及處理響應

 

get與post方式實現Ajax的區別
發送方式 步驟三:初始化XMLHttpRequest對象 步驟四:發送請求
get 指定XMLHttpRequest對象的open()方法中method參數爲「get」 指定XMLHttpRequest對象的send()的data參數爲「null」
post

1.指定XMLHttpRequest對象的open()方法中method參數爲「post」

2.指定XMLHttpRequest對象要請求的Http頭信息,該Http請求頭信息爲固定寫法

指定XMLHttpRequest對象的send()的data參數的值,即該請求須要攜帶的具體數據

 

 需注意採用get方式發送請求時,XMLHttpRequest.send()方法不須要傳遞參數,設爲null便可;採用post方式發送請求時,XMLHttpRequest.send()方法中指定傳遞的參數

 

複製代碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>Ajax驗證用戶名是否存在   post發生請求</title>
    <script type="text/javascript">
    
      //給文本框註冊一個失去焦點事件
    window.onload=function(){
        var dom=document.getElementById("txtName");
          dom.onblur=function(){
             myajax();
          };
    
    };
      
    
    function myajax(){
    
       //01.定製出 xhr對象
       var xhr;
       //02.能力檢測
       if(window.XMLHttpRequest){
           //非IE瀏覽器   
          xhr=new XMLHttpRequest();
       }else{
          //IE內核
          xhr=new ActiveXObject("Microsoft.XMLHttp");
       }
        var dom=document.getElementById("txtName");
        var myspan=document.getElementById("msg");
        var myval=dom.value;
       //03.構建請求地址
       //xhr.open("請求類型","請求地址","是否異步");
       xhr.open("post","<%=path%>/servlet/CheckUserServlet?uname="+myval,true);

       //04.設置回調函數     響應回來的數據
       xhr.onreadystatechange=function(){
         //什麼
         if(xhr.readyState==4&&xhr.status==200){
            //獲取響應數據
            var data=xhr.responseText;
            if(data=='OK'){
                
                 myspan.innerText="用戶名已經被註冊";
            }else{
            
                 myspan.innerText="用戶名能夠註冊";
            }
         }
       };
       
       
       //05.用send真正的發送post請求
       xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       xhr.send("uname"+myval);

       }
       
    </script>
  </head>
  
  <body>
  <h1>Ajax驗證用戶名是否存在   post發生請求</h1>
    用戶名:<input type="text" name="txtName" id="txtName"/> <span id="msg"></span><br/>
    密碼:<input type="password" name="txtPwd"/>
  </body>
</html>
複製代碼

 

效果:

相關文章
相關標籤/搜索