Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Struts2 搭配 AJAX 異步傳送 XML 與 JSON 資料

這兩天把 XML 與 JSON 在 Struts2 中的用法學了一遍,實務上它一定要和 AJAX 搭配,常見場景包括註冊時的帳號唯一性驗證、不刷新整頁就更新局部資料等。

就現況而言 JSON 比 XML 更流行,但可以預期未來一段時間企業系統裡仍會大量存在 XML,所以本文把 XML 的產生與 JS 端的解析一併說明。

原理

前台透過 AJAX 發出請求,後台依請求內容建立要回傳的物件,把物件組裝成 XML 或 JSON 格式送回;JS 收到後解析並渲染到頁面上。熟悉 Web 開發的人對這套流程應該不陌生,它能在不打斷使用者操作的情況下完成資料交換,明顯改善體驗。

第一步:建立工程與 jar 包

新建 web 工程 struts2-ajax,加入對應的 jar 包。

第二步:設定 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="https://java.sun.com/xml/ns/javaee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
    https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
  </filter-mapping>
</web-app>

第三步:寫界面

為了省事,直接在 index.jsp 中修改,用 jQuery 的 $.post 分別呼叫兩個 Action,並把回傳結果拼成表格塞回頁面:

<script type="text/javascript" src="scripts/jquery-1.4.4.js"></script>
<script type="text/javascript">
  function getInfo(){
    $.post("getXMLAction.action",
      { name: $("#name").val() },
      function(returnedData, status) {
        // XML:用 find 取出各節點文字
        var name = $(returnedData).find("name").text();
        var age = $(returnedData).find("age").text();
        var height = $(returnedData).find("height").text();
        var address = $(returnedData).find("address").text();
        var html = "<table width='60%' border='1'>"
          + "<tr><td>name</td><td>age</td>"
          + "<td>height</td><td>address</td></tr>"
          + "<tr><td>" + name + "</td><td>" + age
          + "</td><td>" + height + "</td><td>" + address
          + "</td></tr></table>";
        $("body table:eq(0)").remove();
        $("body").append(html);
      });
  }
  function getJsonInfo() {
    $.post("getJSONAction.action",
      { name: $("#name").val() },
      function(returnedData, status) {
        // JSON:直接以屬性取值
        var html = "<table width='60%' border='1'>"
          + "<tr><td>name</td><td>age</td>"
          + "<td>height</td><td>address</td></tr>"
          + "<tr><td>" + returnedData.name + "</td><td>" + returnedData.age
          + "</td><td>" + returnedData.height + "</td><td>" + returnedData.address
          + "</td></tr></table>";
        $("body table:eq(0)").remove();
        $("body").append(html);
      });
  }
</script>

頁面上放一個 select 與兩個按鈕,分別觸發 getInfo() 與 getJsonInfo() 即可。可以清楚看到兩者的差異:XML 需要 find 節點,JSON 則直接取屬性。

更多細節見下一頁:https://www.linuxidc.com/Linux/2013-08/88247p2.htm

Copyright © Linux教程網 All Rights Reserved