2014-10-07 124 views
0

我使用Spring MVC,但說實話我正在學習它。我想知道(教程,鏈接,任何非常感謝!)什麼是做內容更新的最佳方式,即使用AJAX的div。我試圖做的第一件事是簡單的計算器,它使用2個值,按下按鈕後,我想顯示一個結果div。示例代碼Spring MVC + AJAX內容更新

<form th:method="post" action="" 
     class="form-horizontal" id="bmiForm"> 
     <div class="control-group" th:classappend="${#fields.hasErrors('height')} ? error"> 
      <label class="control-label" th:text="#{bmi.height}" /> 
      <div class="controls"> 
       <input id="height" type="number" min="0" th:field="*{height}" /> <span class="help-inline" th:errors="*{height}">[error]</span> 
      </div> 
     </div> 

     <div class="control-group" th:classappend="${#fields.hasErrors('weight')} ? error"> 
      <label class="control-label" th:text="#{bmi.weight}" /> 
      <div class="controls"> 
       <input id="weight" type="number" min="0" th:field="*{weight}" /> <span class="help-inline" th:errors="*{weight}">[error]</span> 
      </div> 
     </div> 

     <div id="data" th:fragment="bmiResult"> 
      // I'd like this content to be hidden at beginning and display the result, after handling by a controller. 
      <span id="randomid" type="text" th:text="${user.bmi}" /> 
     </div> 

     <div class="form-actions"> 
      <button type="submit" id="calculateBmi" name="_eventId_calculateBmi" class="btn btn-primary" th:text="#{calculate}" /> 
     </div> 
    </form> 

回答

2

基本上使用html()函數在特定函數完成時更新div。 但是接下來還有其他方法可以使用ajax進行更新,具體取決於您的要求如追加。您可以專注於單個元素或刷新整個頁面。

我個人的目標是爲了簡單和有效的個人divs。

這裏是一個例子How to update a specific div with ajax and jquery

簡單的例子

<html> 
//random html code 
<div id="calculator_result">Result</div> 

<a href="javascript;:" onClick="calculateResult()">Click Me</a> 
</html> 

//ajax functions 
<script> 
function calculateResult() { 
$("#calculator_result").html("23"); 
} 
</script> 

上面的例子應該將23與ID calculator_result股利。

希望有所幫助。如果您需要更多信息,請讓我知道並不適合您。

+0

下一個問題是如何通過控制器來處理它 - 作爲一個帶參數的get方法?嘗試這樣的事情,但我有以下錯誤:「發現不明確的映射」,因爲兩個方法被定義爲相同的路徑。 – 2014-10-08 10:37:04

+1

有很多方法,最簡單的方法是使用RestController註釋。通過這種方式,您可以像使用普通控制器一樣在restcontroller中創建函數,而所有RestController所做的都是從JSON轉換到/從JSON轉換。谷歌上的文檔和示例堆。如果你努力發表一個問題(因爲它現在是主題),我會爲你提供更多的數據。 – Aeseir 2014-10-08 11:03:25

+0

我使用thymeleaf,它是特定的標籤,所以我可以準備div,它只需要結果並且param hidden =「true」,然後在ajax調用之後進行一些很好的轉換並將隱藏的參數更改爲false? – 2014-10-08 14:17:54