由於開發工作需要,近期研磨了在Struts2架構下使用Jquery Ajax的技術。現以表單的提交為例,簡單現總結如下:1、jsp檔案<script type="text/javascript" src="JS/jquery-1.9.1.min.js"></script> <script type="text/javascript" > $(function(){ $("#btn1").click(function(){
$.ajax({
url:'ajaxActionName.action', //提交目標,幕後處理action
dataType:'json',
type:'post',
data:{ txtStr: $("#txt").val()}, //擷取文字框的值作為參數
success:showResult //設定action執行成功後的動作函數 }); });});function showResult(data) //data為action所返回的值 { alert(data.result); //result是action中用作傳回值的一個變數 }</script><input id="txt" type="text" /><br><input id="btn1" type="button" value="btn1" /> 2、struts.xml<package name="test" extends="json-default"> <action name=" ajaxActionName " class="com.btnAction"> <result type="json"></result> </action> </package>3、action: btnAction.javapackage com;import com.opensymphony.xwork2.ActionSupport;public class btnAction extends ActionSupport{private String result; private String txtStr ;public String getResult(){return this.result;}public void setResult(String tmp){this.result=tmp;}public String getTxtStr (){return this.txtStr ;}public void setTxtStr(String tmp){this.btn1=tmp;}public String execute() throws Exception{this.result=this.btn1; //擷取所傳來的文字框的值,賦給result變數,返回給ajaxreturn SUCCESS;}}