struts2 json jquery 集成詳解

Struts2 下使用 jsonplugin jquery 完成 ajax 功能
 
1.      如下網址[url]http://code.google.com/p/jsonplugin/downloads/list[/url]下載JSON插件的JAR包(新版本是0.32),並加到工程的相應目錄下。從以下網址[url]http://docs.jquery.com/Downloading_jQuery[/url]下載jquery所需文件。(建議下載穩定版本,否則會出現莫名其妙的錯誤)
2.      配置相應的xml文件,爲ajax請求提供數據:
<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd" >
< struts >
    < package name = "sajax" extends="json-default" namespace = "/book" >
        < action name = "getAjaxBookChannelList" method = "getAjaxBookChannelList" class = "bookChannelAction" >
            <result type="json" />
        </ action >
        < action name = "getAjaxBookCategoryListByChannelID" method = "getAjaxBookCategoryListByChannelID" class = "bookChannelAction" >
            < result type = "json" />
        </ action >
    </ package >
</ struts >
配置有兩處與一般的action配置不一樣,一處是擴展了 json-default json-default」是在jsonplugin-0.30.jar包裏的struts-plugin.xml中定義的,文件內容以下:
<?xml version="1.0" encoding="UTF-8" ?>
 
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <package name="json-default" extends="struts-default">
        <result-types>
            <result-type name="json" class="com.googlecode.jsonplugin.JSONResult"/>
        </result-types>
        <interceptors>
            <interceptor name="json" class="com.googlecode.jsonplugin.JSONInterceptor"/>
        </interceptors>
    </package>
</struts>
 
另外一處是定義了返回類型爲json <result type="json" /> ,會將response中的返回數據轉化爲json對象。
3.在Action中的定義。定義返回對象,並添加getset方法。返回的數據能夠根據須要格式成json形式(json格式如{1:test,2:test}),好比爲二級列表提供填充內容的的數據,在頁面須要進行遍歷,作成json形式的,在頁面遍歷時也會比較方便。Action代碼(部分)以下:
   
    public String getAjaxBookChannelList() {
       StringBuffer sb = new StringBuffer();
       bookChannelList = bookService .getBookChannelList();
       if ( bookChannelList .size() > 0) {
           int j = bookChannelList .size();
           sb.append( "{" );
           for ( int i = 0; i < j; i++) {
              BookChannel bc = (BookChannel) bookChannelList .get(i);
              sb.append(bc.getId());
              sb.append( ":" );
              sb.append( "\"" );
              sb.append(bc.getName());
              sb.append( "\"" );
              if (i != (j - 1))
                  sb.append( "," );
           }
           sb.append( "}" );
       }
 
       strAjaxChannel = sb.toString();// 返回的數據
 
       return Action. SUCCESS ;
    }
 
 
4 頁面操做。Jquery中已經提供幾供ajax請求的方法,若是返回的是json對象,使用jQuery.getJSON(url,[data],[callback])會比較方便,
 
jQuery.getJSON(url,[data],[callback]) 經過 HTTP GET 請求載入 JSON 數據。
 
返回值
XMLHttpRequest
 
參數
url (String) : 發送請求地址。
data (Map) : (可選) 待發送 Key/value 參數。
callback (Function) : (可選) 載入成功時回調函數。
 
參數部分瀏覽器的緩存是以url爲標識的,若是url相同會使用緩存中的數據,若是不想使用緩存,能夠在參數中加入一個隨機數。
 
jQuery.each(obj,callback)
通用例遍方法,可用於例遍對象和數組
參數
object (Object) : 須要例遍的對象或數組。
callback (Function) : (可選) 每一個成員/元素執行的回調函數。
回調函數擁有兩個參數:第一個爲對象的成員或數組的索引,第二個爲對應變量或內容。
Jquery操做下拉列表添加選項的方法爲: $(「# categoryId」)[0].options.add(option);
 
頁面代碼以下(部分):
<. language="." type="text/." src="/.s/jquery- 1.2.2 .js"></.>
<. language=".">
       function fillChannel(id){
              var url = "/book/getAjaxBookChannelList.action";
              $.getJSON(url,{ran:Math.random()},function(json){
                     if(json.strAjaxChannel.length > 0){
                            var obj = .('(' + json.strAjaxChannel + ')');
                            $.each(obj,function(i,n){
                          option = new Option(n,i);
                          if(i==id)option.selected=true;
                         document.getElementById("channellistId").options.add(option);
                      });
                      option = new Option("所有頻道",999);
                      if(id == 999)option.selected=true;
                      document.getElementById("channellistId").options.add(option); 
                  }
               else{
                           option = new Option("暫無頻道");
                           document.getElementById("channellistId").options.add(option);
                  }
                     }
              );    
       }
       function fillCategory(chid,bid){
              document.getElementById("categoryId").options.length=1;
              var url = "/book/getAjaxBookCategoryListByChannelID.action";
              var cid = 0;
              if(chid > 0){
                     cid = chid;
              }
              else{
                     cid = document.getElementById("channellistId").value;
              }
              $.getJSON(url,{channelID:cid,ran:Math.random()}, function(json){
        //參數爲頻道ID及隨機數,function(json)爲回調函數,其中json爲取到的返回數據
                       if(json.strAjaxCategory.length > 0){
                                   var obj = .('(' + json.strAjaxCategory + ')');//json文本轉化爲json對象,以便於遍歷
                                   $.each(obj,function(i,n){  //jquery中的遍歷方法,
                                 option = new Option(n,i);
                                 if(i==bid)option.selected=true;
                                document.getElementById("categoryId").options.add(option);
                             });
                                  option = new Option("所有分類","-3");
                                  if(bid ==-3)option.selected=true;
                                  document.getElementById("categoryId").options.add(option);
                                  //jquery的方法爲:$(# categoryId)[0].options.add(option);
                  }
                  else{
                           if(cid == 999){
                                  option = new Option("所有分類","-1");
                                  document.getElementById("categoryId").options.add(option);                              
                           }
                           else{
                                  option = new Option("暫無分類");
                                  document.getElementById("categoryId").options.add(option);
                           }
                  }
                     }
              );           
       }
 
       function fillSelect(chid,cid){
              fillChannel(chid);
              fillCategory(chid,cid);
       }
</.>
<body <s:if test="bookCategory.bookchannelId >0">onLoad="fillSelect(<s:property value="bookCategory.bookchannelId"/>,<s:property value="bookCategory.id"/>);"</s:if><s:if test="bookCategory==null">onLoad="fillChannel(0);"</s:if>>
 
做品類別
         < select name = "channellistId" id = "channellistId" onChange = "fillCategory(<s:if test="bookCategory.bookchannelId >0">0,</s:if><s:property value="categoryId"/>);"><option> 選擇頻道 </ option ></ select >
         < select name = "categoryId" id = "categoryId" >< option > 選擇分類 </ option ></ select >
 
 
獲得以下內容:
{"ajaxBookCategoryListByChannelID":"success","ajaxBookChannelList":"success","bcID":0,"bchID":0,"bookCategory":null,"bookCategoryAllList":null,"bookCategoryByChannelID":"success","bookCategoryByID":null,"bookCategoryList":null,"bookCategoryListModel":null,"bookChannel":null,"bookChannelList":[{"createdate":" 2008-07-09 T10:23:36","id":1,"name":"暢銷經典","prefix":"changxiao","status":0},{"createdate":" 2008-07-09 T10:24:03","id":2,"name":"玄幻奇幻","prefix":"yy","status":0},{"createdate":" 2008-07-09 T10:24:25","id":3,"name":"都市娛樂","prefix":"dushi","status":0},{"createdate":" 2008-07-09 T10:24:38","id":4,"name":"歷史軍事","prefix":"ss","status":0},{"createdate":" 2008-07-09 T10:24:54","id":5,"name":"女性時尚","prefix":"nvxing","status":0},{"createdate":" 2008-07-09 T10:25:11","id":6,"name":"遊戲競技","prefix":"dongman","status":0},{"createdate":" 2008-07-09 T10:25:24","id":7,"name":"恐怖靈異","prefix":"kongbu","status":0},{"createdate":" 2008-07-09 T10:25:35","id":8,"name":"文化社科","prefix":"www","status":0},{"createdate":" 2008-07-09 T10:25:46","id":9,"name":"經管勵志","prefix":"www","status":0}],"channelID":0,"currentPage":0,"info":"","msg":"","pageSize":0,"srcID":0,"strAjax":"","strAjaxCategory":"","strAjaxChannel":"{1:\"暢銷經典\",2:\"玄幻奇幻\",3:\"都市娛樂\",4:\"歷史軍事\",5:\"女性時尚\",6:\"遊戲競技\",7:\"恐怖靈異\",8:\"文化社科\",9:\"經管勵志\"}","tarID":0,"theBookCategory":"success","theBookChannel":"success","toID":0}
 
 
 
 
關於jsonplugin序列化的幾點:
a.對於不想被序列化的屬性,能夠在他的get方法前加註釋:      @JSON(serialize=false)
b.對於想改變json結果屬性名稱的,能夠在他的get方法前加註釋@JSON(name="屬性名")
c. 帶有transient修飾符與沒有Getter方法的字段(field)都不會被串行化爲JSON
 
 
對於struts2jsonpluginjquery的使用,我也不太熟悉,你們一塊兒學習吧。
 
 
參考資料:
 
Struts 2AJAX
[url]http://hi.baidu.com/clking419/blog/item/503abb18079b250535fa41b5.html[/url]
相關文章
相關標籤/搜索