ajax交互的兩種方式:html與xml


對比jquery對這兩種交互的實現:

基於html交互:

function verify(){
    //解決中文亂碼問題的方法 1,頁面端發出的數據做一次encodeURI,服務器端使用 new String(old.getBytes("iso8859-1"),"utf-8")
    //var url= "AJAXServer?name="+encodeURI($("#userName").val() ) ; // encodeURI處理中文亂碼問題
   // 解決中文亂碼問題的方法 2.頁面端發出的數據做兩次encodeURI處理, 服務器端用URLDecoder.decode(old,"utf-8");
    var url= "AjaxServer?name="+encodeURI(encodeURI($("#userName").val() )); // encodeURI處理中文亂碼問題
    url=convertURL(url);//獲取函數的返回值'login?uname='+ uname + '&psw=' + psw
          $.get(url,null,function(data){
              $("#result").html(data); //簡潔版
          });
System.out.println(url);
}
//給URL增加時間戳,騙過瀏覽器,不讀取緩存
function convertURL(url){
    //獲取時間戳
   var timstamp=(new Date()).valueOf();
    //將時間戳信息拼接到URL上
    if(url.indexOf("?")>=0){//用indexof判斷該URL地址是否有問號
    url=url+"&t="+timstamp;
    }else{
       url=url+"?t="+timstamp;  
    }
   return  url;

}

后台頁面:

package com.xidian.ajax;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
public class AjaxServer extends HttpServlet {
        protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
                throws ServletException, IOException {
            try{
              httpServletResponse.setContentType("text/html;charset=utf-8"); 
              PrintWriter out= httpServletResponse.getWriter();
                
               Integer inte = (Integer)httpServletRequest.getSession().getAttribute("total"); //用來測試緩存的;在IE下如果多次請求的地址相同,則他不會再去服務器端交互讀數據,而是直接讀取緩存
                  int temp=0;
                if(inte==null){
                    temp=1;
                }else{
                    temp=inte.intValue()+1;
                }
                   httpServletRequest.getSession().setAttribute("total",temp);
               //1.取參數
           String old =httpServletRequest.getParameter("name");
               // String name=new String(old.getBytes("iso8859-1"),"utf-8"); //處理中文亂碼1,需和前台js文件中的encodeURI配合
               String name= URLDecoder.decode(old,"utf-8"); //處理中文亂碼2
              //2.檢查參數是否有問題
          if(old==null||old.length()==0){
              out.println("用戶名不能為空!");
          } else{
              //String name=old;
              //3.校驗操作
              if(name.equals("123")){
                    //4.與傳統應用不同的是,這一步將用戶感興趣的數據返回給頁面端。而不是將一個新的頁面返回給頁面端
                  //寫法沒有改變,本質變化了
                  out.println("用戶名【"+name+"】已經存在,請使用其他的用戶名!,"+temp);
              } else{
                  out.println("用戶名【"+name+"】未存在,您可以使用該用戶名!,"+temp);
              }
          }
        }catch(Exception e){
               e.printStackTrace();
            }
        }

        protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws ServletException, IOException {
           doGet(httpServletRequest,httpServletResponse);
        }
    }

以上實現的基於html是比較常用的,而比較的簡單;

下面我們實現基於XML交互來實現:js:

//定義用戶名校正的方法
function verify(){
    //首先測試下頁面的按鈕按下,可以調用這個方法
    //使用javascript里的alert方法,顯示個彈出提示框
   // alert("按鈕被按下"); 測試是否已進到了js內
    //1獲取到文本框中的內容
   // document.getElementById("username") dom的獲取方法
    //jquery查找節點的方式,參數中的#加id參數值可以找到一個節點
    //jquery的方法返回的都是jquery的對象,可以在上面繼續執行其他的jquery方法

   var jqueryObj= $("#userName")
    //獲取節點的值
    var userName=jqueryObj.val();
   // alert(userName);測試是否得到username
    //2.將文本框的數據發送給服務器端的servlet
    //javascript當中,一個簡單對象的定義方法
     // var obj={name:"123",age:30}
    //使用jquery的XMLHttprequest對象get請求的封裝

 $.ajax({
     type:"post",     //http請求方式
     url:"AjaxXmlServer",     // 服務器端url地址
     data:"name="+userName,  //  發送給服務器的數據
      dataType:"xml",//告訴服務器返回的數據類型
     success:callback //定義交互完成,並且服務器正確返回數據時調用的回調函數
 })
    

}
//回調函數,data為服務器端返回的數據
function callback(data){
   //alert("服務器端的數據回來了");測試與服務器端的交互
     //3.接受服務器端返回的數據
  // alert(data); 測試data
    //需要將data這個dom對象中的數據解析出來
    //首先需要將dom對象轉化為jquery對象
    var jqueryObj=$(data);
    //獲取message節點
    var messsage= jqueryObj.children();
    //獲取文本內容
    var text=message.text();//這里獲得的是所有子節點的返回值,因為message返回的是一個數組
    //4.將服務器端返回的數據動態的顯示在頁面上
  // 找到保存數據的節點
    var resultObj=$("#result");
    //動態的改變頁面中div的內容
    resultObj.html(data);

}

后台的代碼:

package com.xidian.ajax;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;

public class AjaxXmlServer extends HttpServlet {

        protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
                throws ServletException, IOException {
            try{
                //修改點1----響應的 Content-Type必須是text/xml,這很重要
           httpServletResponse.setContentType("text/xml;charset=utf-8");
           PrintWriter out= httpServletResponse.getWriter();
               //1.取參數
           String old =httpServletRequest.getParameter("name");
              //2.檢查參數是否有問題
                 //修改點2----返回的數據需要封裝成xml格式
            StringBuilder builder=new StringBuilder();
            builder.append("<message>"); //XML的返回內容要包含在<message></message>
       
          if(old==null||old.length()==0){//要驗證接受的文本框內容是否為空
              builder.append("用戶名不能為空!").append("</message>");
          } else{
              String name=old;
              //3.校驗操作

              if(name.equals("123")){
                    //4.與傳統應用不同的是,這一步將用戶感興趣的數據返回給頁面端。而不是將一個新的頁面返回給頁面端
                  //寫法沒有改變,本質變化了
                  builder.append("用戶名【"+name+"】已經存在,請使用其他的用戶名!").append("</message>");
                 // out.println("用戶名【"+name+"】已經存在,請使用其他的用戶名!");
              } else{
                 // out.println("用戶名【"+name+"】未存在,您可以使用該用戶名!");
                  builder.append("用戶名【"+name+"】未存在,您可以使用該用戶名!").append("</message>"); 
              }
              out.println(builder.toString());//這是必須的
              System.out.println("輸出內容為:"+builder.toString());//輸入sout后按Tab鍵會自動生成
          }


        }catch(Exception e){
               e.printStackTrace();
            }
        }

        protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws ServletException, IOException {
           doGet(httpServletRequest,httpServletResponse);
        }
    }

我已經將兩種方式的不一樣的點全部標注出來了,大家可以對比下,使用自己比較能接受的那種方式;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM