2013-12-08 44 views
0

我的Ajax調用有問題。 這裏是我的控制器:Ajax post請求調用不起作用

@RequestMapping(value = { "/sendMsg" }, method = RequestMethod.POST) 
public ModelAndView postSendMessage(@ModelAttribute("message") MsgParam param) { 
ModelAndView result= new ModelAndView("sendMessage"); 
...Controller logic... 
} 

我在sendMessage.jsp的形式,應該返回JSON。然而,ajax調用不起作用,所以現在我試圖通過ajax調用來返回html,這對用戶沒有任何影響。我現在要做的就是用html返回一個簡單的ajax調用。 這裏是我的JSP形式:

<form:form id="postForm" method="POST" commandName="message" action="${pageContext.request.contextPath}/sendMsg"> 
    ... input fields with path attributes... 
</form:form> 

可正常工作,所以這就是爲什麼省略的邏輯。 我嘗試添加下面的腳本後的形式:所以現在

<script> 
     $('#postForm').submit(function(evt) { 
       evt.preventDefault(); 
       alert("ajax"); 
       msgData = $('#postForm').serialize(); 
       $.ajax({ 
       url: $('#postForm').action, 
       type: 'POST', 
       data: msgData 
       }); 
     }); 
    </script> 

當我嘗試提交表單和以前一樣,我得到的AJAX調用前阿賈克斯警報彈出,但沒有發送頁面POST請求和什麼都沒發生。有誰知道什麼是錯的?

非常感謝..

+0

在控制檯中的任何錯誤都支持? – epascarello

+0

您的表單元素是否具有「名稱」屬性?我發生過幾次jQuery的表單序列化方法。 –

+0

在控制檯中沒有錯誤.. – user3080263

回答

0

試試這個檢查你所發送和接收:

<script type="text/javascript"> 
//Wait for jQuery to be loaded 
$(function(){ 

function _submitHandler(evt){ 
      evt.preventDefault(); 
      //form data placeholder 
      var formData={}; 
      //Serialize the form as an array of objects{name and value} 
      var msgData = $('#postForm').serializeArray(); 
      //fill the formData object with name:value pairs 
      //from the serialized array 
      for(var i=0, l=msgData.lenght; i<l; i++){ 
       formData[msgData[i].name]=msgData[i].value; 
      } 
      //Prepare ajax Object 
      var ajaxObj = { 
       url: $('#postForm')[0].action, 
       type: 'POST', 
       data: formData 
      }; 
      //Inspect ajax object in console 
      console.log("Ajax Call"); 
      console.log(ajaxObj); 
      $.ajax(ajaxObj,function(response){ 
       console.log("Server Response"); 
       console.log(response);}); 
      } 
$('#postForm').submit(_submitHandler); 

}); 
</script> 

對於URL,你需要分類指數jQuery的URL:$( '#postForm') 0] .action或獲取屬性url:$('#postForm')。attr('action');顯然第二個將只是路徑,第一個會給你整個URL。如果你這樣做的for循環,可以跳過:

$("#postForm").serializeArray().forEach(function(el){formData[el.name]=el.value}); 

使用forEach的問題是,是不是所有的瀏覽器**

+0

好吧,所以這就是我得到的event.returnValue已被棄用。請改用標準的event.preventDefault()。 jquery-1.9.1.js:3345 Ajax Call login:30 Object {url:undefined,type:「POST」,data:「sender = 1&receivers = 2&body = aageg」}但它仍然不會發布頁面。參數是有效的 – user3080263

+0

@ user3080263嗯..有趣的是你得到一個未定義的url ... –

+0

這只是一個語法問題..這是輸出Ajax調用登錄:30 對象{url:「https:// localhost:8443/MsgManagement/receive」,輸入:「POST」,data:「sender = 1&receivers = 2&body = ageg」},這就是罰款 – user3080263