在頁面跳轉使用者體驗設計時,讓我們討論了一個下午。最後採用一個試用方案,用ajax非同步實現,通過json傳輸資料。這樣對原來的商務邏輯改動很少,這裡我們使用的是struts2,大多工作是修改設定檔。來看看我做的一個demo。
準備:在原來的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="#"
onclick="remove('f1','templateDelete.html?templates.id=${id }',this);return false">
這裡‘href’屬性我們用了“#”,最好用javascript:; 或者 javascript:void(0);但這裡也無所謂了,因為在onclick中我加了return false,在ie和ff測試通過。url後面也無“#”