準備:在原來的struts2的基礎上只有添加jsonplugin.jar插件就可以了.算是安裝吧。
修改配置:
在struts.xml文件中:
修改前:
<package name="default" extends="struts-default">
<interceptor-stack name="rootAdminOnly">
.....
.......
</interceptor-stack>
<action name="templateDelete" class="com.reyosoft.app.webapp.action.BotTemplateAction" method="delete">
<interceptor-ref name="rootAdminOnly"/>
<result name="success" type="redirect-action">templateList</result>
</action>
...
......
修改後:
<package name="default" extends="struts-default">
<interceptor-stack name="rootAdminOnly">
.....
.......
</interceptor-stack>
...
......
<package name="json" extends="json-default,default">
<action name="templateDelete" class="com.reyosoft.app.webapp.action.BotTemplateAction" method="delete">
<interceptor-ref name="rootAdminOnly"/>
<result type="json"/>
</action>
</package>
從修改的結果我們知道,修建了一個包json,因爲這個包需要繼承json-default包,另外我們這裏還繼承了default包,是因爲我們需要調用default包中我們定義的攔截器。
我們的處理結果轉向視圖修改爲了json,
代碼修改:
我們在基類中BaseAction定義了一個json返回消息
/** msg for json */
protected String jsonMsg;
public String getJsonMsg() {
return jsonMsg;
}
public void setJsonMsg(String jsonMsg) {
this.jsonMsg = jsonMsg;
}
在具體類中,BotTemplateAction中,重載了父類方法。
public String getJsonMsg() {
return super.jsonMsg;
}
這麼做到的道理:json插件默認情況下不支持父類屬性方法。
JS修改:
/**
* wrap message with label 'div' make them show like old.
*/
function wrapMsg(msg){
var rt = '<div class=message id=successMessages>'
+ ' <img src="images/iconInformation.gif" alt="icon.information" class="icon" /> '
+ msg
+ '</div>';
return rt;
}
/**
* json call action operation.
* @param fid the form id
* @param url the form action
* @param cur the curent dom element
*/
function remove(fid, url, cur){
var params = $("#"+fid).formToArray();
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
timeout: 1000*60,
data: params,
error: function(){alert('Sorry! Server doesn/'t work well or request time out!');},
success: function(data){
//convert string to json object
var json=eval('('+data+')');
//filter
if(json.showFlag == "0")
$(cur).parent().parent().animate({opacity:'hide'},"slow");
// show msg
$("#msg").html("").append(wrapMsg(json.jsonMsg));
}
});
}
HTML修改:
<a target="_self" href="#"
οnclick="remove('f1','templateDelete.html?templates.id=${id }',this);return false">
這裏‘href’屬性我們用了“#”,最好用javascript:; 或者 javascript:void(0);但這裏也無所謂了,因爲在onclick中我加了return false,在ie和ff測試通過。url後面也無“#”