Struts2+ajax+json整合簡介__js

來源:互聯網
上載者:User

一、準備好jar包,不要小看這一步,萬事開頭難。。總結起來有以下三種搭配。

1.   xwork-core-2.1.6.jar和struts2-json-plugin-2.1.8.jar。如果你想使用struts2-json-plugin-2.1.8.jar這種支援方式,你的xwork-core-*.jar不能選擇2.2.1及以上版本,因為xwork-core-*.jar的2.2.1及以上版本中沒有了org.apache.commons.lang等包。啟動tomcat的時候會出現:java.lang.NoClassDefFoundError: org.apache.commons.lang.xwork.StringUtils。

 

2.   xwork-2.1.2.jar和jsonplugin-0.34.jar。如果想用jsonplugin-0.34.jar這種支援方式,那需要切換你的xwork-core-*.jar為xwork-2.1.2.jar。因為jsonplugin-0.34.jar需要com.opensymphony.xwork2.util.TextUtils

這個類的支援。而xwork-core-*.jar的2.2.1以上版本均為找到該類,且在xwork-core-2.1.6.jar中也沒有該類。


3 .struts2.3.7的版本,適合struts2-json-plugin-2.3.4.1.jar與json-lib-2.3-jdk15.jar


二、下面看下action是啥吧。

public String editProblem(){question=(Question) this.getSession().get("QUESTION_INFO");this.pid=String.valueOf(question.getId());question.setContent(this.newContent);question.setModifyDateTime(this.getCurrentDate());showProblemsLogic.updateProblem(question);//更新資料庫記錄return SUCCESS;}

很簡單,是個編輯問題的方法,筆者正在做一個互動問答平台,使用者在提問之後,還可以編輯自己的問題。
上面就是實現這個功能的action代碼。可以注意到,這個action裡面有很多屬性,struts.xml可以這樣寫。

<action name="editProblem" class="problemsAction" method="editProblem">          <result name="input">/problems.jsp</result>          <result type="json">          <param name="includeProperties">newContent</param>           </result>                   </action> 

includeProperties這個參數的配置對應的是下面這段ajax提交代碼中的success回呼函數中的data,如果data需要更多的內容,則可以在includeProperties參數裡面添加更多的屬性。  這個參數的配置很關鍵,配置錯了,success回呼函數就不會執行了,所以一定要注意。


三、再來看下ajax函數是怎麼寫的吧

<script>$(document).ready(function(){   $("#edit_content_button").click(function() {        var params = $("#edit_form").serialize();//講指定表單中的參數轉換為查詢字串//使用jQuery中的$.ajax({});Ajax方法$.ajax({url:"editProblem",//這個是對應的action名稱type:"POST",data:params,dataType:"json",success:function(data){ajax請求提交成功後的回呼函數$("#qcontent").css("display","none");$("#newqContent").empty();$("#newqContent").append(data.newContent);$('#edit_form').toggle();alert("修改成功。");},error:function(data){alert(arguments[1]);}});    });});</script>

這樣,整合就算初具規模了,可以實現在struts2下,頁面無重新整理的表單提交了~



 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.