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中的定义。定义返回对象,并添加get,set方法。返回的数据可以根据需要格式成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>
 
 
直接访问[url]http://manager.17k.com/book/getAjaxBookChannelList.action[/url]
得到如下内容:
{"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-09T10:23:36","id":1,"name":"畅销经典","prefix":"changxiao","status":0},{"createdate":"2008-07-09T10:24:03","id":2,"name":"玄幻奇幻","prefix":"yy","status":0},{"createdate":"2008-07-09T10:24:25","id":3,"name":"都市娱乐","prefix":"dushi","status":0},{"createdate":"2008-07-09T10:24:38","id":4,"name":"历史军事","prefix":"ss","status":0},{"createdate":"2008-07-09T10:24:54","id":5,"name":"女性时尚","prefix":"nvxing","status":0},{"createdate":"2008-07-09T10:25:11","id":6,"name":"游戏竞技","prefix":"dongman","status":0},{"createdate":"2008-07-09T10:25:24","id":7,"name":"恐怖灵异","prefix":"kongbu","status":0},{"createdate":"2008-07-09T10:25:35","id":8,"name":"文化社科","prefix":"www","status":0},{"createdate":"2008-07-09T10: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。
 
 
对于struts2下jsonplugin、jquery的使用,我也不太熟悉,大家一起学习吧。
 
 
参考资料:
 
Struts 2与AJAX
[url]http://hi.baidu.com/clking419/blog/item/503abb18079b250535fa41b5.html[/url]

你可能感兴趣的:(jquery,游戏,Ajax,json,struts)