从以下网址
http://code.google.com/p/jsonplugin/downloads/list下载JSON插件的JAR包(新版本是0.32),并加到工程的相应目录下。从如下网址
http://docs.jquery.com/Downloading_jQuery下载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;
}