2013-03-17 39 views
2

我想在spring mvc中的form中實現基於ajax的post。不能在春天mvc表格中使用ajax

這裏是我的代碼:

<form:form method="POST" commandName="emailDomain"> 
    <form:textarea path="emailText" rows="5" id="emailList" 
     placeholder="Write emails to submit us, saperated by ';'" 
     style="width: 100%" /> 

<form:select items="${categoryMap}" path="categoryId" id="categoryList" 
    onchange="showEmails()" /> 

    <br /> 
    <p align="center"> 
     <button type="button" value="Submit" id="submitEmails">Submit emails</button> 
    </p> 
    <p align="center" class="text-info">${var}</p> 
</form:form> 

我的Ajax代碼是:

<script type="text/javascript" 
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 

    <script type="text/javascript"> 
    function showEmails() { 

      var categoryId = $('#categoryList').val(); 
    var emailText = $('#emailList').val(); 

    $.ajax({ 
     type : "POST", 
     url : "http://localhost:8081/chatbooster/forms/email.html?cat=1", 
       data : "categoryId=" + categoryId + "&emailText=" + emailText, 
     success : function(response) { 


     }, 
     error:function (xhRequest, ErrorText, thrownError) { 
      alert('Error: ' + ' ' + thrownError); 
     } 
    }); 
} 

的問題是點擊該按鈕後,它會顯示錯誤的警報,但與任何解釋。之後,它跳轉到顯示json響應的頁面。如果我根本不使用彈簧表單標籤,代碼將起作用。它不會顯示錯誤,並且不會顯示json響應,但是再次,我將無法從數據庫填充選擇下拉菜單。

我的控制器:

@Controller 
    @RequestMapping(value = "/email.html") 
    public class EmailController{ 

    @RequestMapping(method = RequestMethod.GET) 
     public String showForm(Model model, 
      @RequestParam(value = "cat", required = true) String category, 
      HttpServletRequest request, HttpServletResponse response) { 
     clearSession(request, response); 

     return "email"; 
     } 

    @RequestMapping(value = "/submitemails", method = RequestMethod.GET) 
     public @ResponseBody 
     String submitAndRefreshEmails() { 
     System.out.println("check"); 

     return "email"; 
     } 

    @RequestMapping(method = RequestMethod.POST) 
     public @ResponseBody 
     EmailJsonResponse addEmail(@Valid EmailDomain emailDomain, 
      BindingResult result, 
      @RequestParam(value = "cat", required = true) String category, 
      HttpServletRequest request, HttpServletResponse response) 
     throws Exception { 

     //return emailjsonresponse object, a simple object carrying few ints and strings 

     } 

    @ModelAttribute("categoryMap") 
     public Map<Long, String> populateCategoryList(
      @RequestParam(value = "cat", required = true) String category) 
     throws Exception { 

     // populating drop down 

     } 

    } 

我看過很多討論這個,但我沒能獲得如何使它像這樣的情況?任何人都可以請幫我在這裏?我指的這個例子http://www.javacodegeeks.com/2012/02/spring-mvc-and-jquery-for-ajax-form.html

編輯1:

我甚至試過這種新:

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#submitEmails').onclick(function() { 
      $.getJSON('http://localhost:8081/chatbooster/forms/submitemails.html?cat=1', 
       { 
        categoryId : $('#categoryList').val(), 
        emailText : $('#emailList').val(), 
        ajax : 'true' 
       }, 
       function(data) { 
        alert('data found'); 
       } 
     ); 
     }); 
    }); 

但是還是我正在顯示JSON響應。我無法理解爲什麼會發生?我試過這http://rockhoppertech.com/blog/spring-mvc-3-cascading-selects-using-jquery/。當我不使用彈簧表單組件時,我能夠實現ajax。但是這會給我填充數據庫中的下拉元素帶來麻煩。有一些我錯過了。任何想法可能是什麼?

編輯2

現在我明白了,這是什麼問題的原因。這是我提交的形式,最終導致我json的迴應。我需要做的是從按鈕調用jquery函數,使按鈕類型的提交按鈕,而不是提交類型。點擊它將調用與控制器的GET請求類型相關的方法。但爲此,我需要在點擊提交按鈕時調用submitAndRefreshEmails方法。任何人都可以請告訴我該怎麼做?如何在控制器中有許多這種類型的方法時調用GET類型的特定方法?

+0

該頁面是否也從'http:// localhost:8081 /'加載?否則,您的請求會違反SOP。嘗試設置'crossDomain'參數。 – CBroe 2013-03-17 00:29:07

+0

@vlad halmer在你的ajax調用中,我沒有看到'data'被提交?看起來像你的'addEmail'方法期待一個有效的'EmailDomain'對象... – user1766760 2013-03-17 01:36:07

+0

@ user1766760正如你所說,我已經在我的ajax調用中添加了數據:「categoryId =」+ categoryId +「&emailText =」+ emailText。因此,控制器能夠從視圖中獲取數據,但在提交表單後,頁面顯示json響應。我在視圖頁面中編輯了ajax調用。 – 2013-03-17 15:24:45

回答

0

由於您正在進行AJAX調用,因此您希望在不重新加載HTML頁面的情況下返回信息摘錄(您的JSON數據)。因此使用@ResponseBody

如果AJAX調用綁定到一個表單提交,它會觸發一個頁面加載(我似乎無法找到一個很好的來源解釋這一點)。因此,您需要停止默認行爲。

$form.bind('submit', function(e) { 
    $.post('epdReviewSaveChanges.json', mData, function(response) { 
      //do stuff... 
    } 

    e.preventDefault(); 
    return false; 
}); 

對上述的一些解釋取自here

e.preventDefault()該代碼的一部分阻止瀏覽器執行默認操作。 return false;需要進一步研究,因爲它還可以防止該事件傳播(或「冒泡」)DOM。

我懷疑你原來的問題有更多與如何使用AJAX調用/春。我不是在談論任何跨域問題,這可能需要額外的/不同的解決方案。

問題2作爲映射到控制器內的具體方法,可以使用value的不同的呼叫之間進行區分。例如:

@RequestMapping(value="/Upload.html",method = RequestMethod.POST) 
+0

謝謝你的迴應...我沒有使用preventDefault來解決我的問題,但是我已經映射了不同的值給我的方法返回Json響應,並且該方法在不同的控制器 – 2013-03-24 19:29:48