2015-11-21 29 views
1

我對Ajax有點新,我試圖提交一個窗體使用jQuery,Ajax和百里香的視圖。我知道後鏈接的作品,因爲如果我只是告訴ajax提交一旦頁面加載任何形式提交給數據庫沒有問題,但如果我嘗試使用提交按鈕,然後表單變爲空白,並且url更改爲類似http://localhost:8080/viewCourse/post/1?_csrf=d512fb5c-08e5-4373-895e-1297b0c35a4b的東西,並且沒有任何內容進入數據庫,但控制檯中也沒有錯誤,因此我不確定發生了什麼。jquery Ajax表單不提交和url顯示csrf標記

這裏是我的jQuery和AJAX

var postId = /*[[${post.id}]]*/'1'; 

var token = $("meta[name='_csrf']").attr("content"); 
var header = $("meta[name='_csrf_header']").attr("content"); 

$(document).ajaxSend(function(e, xhr, options) { 
    xhr.setRequestHeader(header, token); 
}); 

$("#submit").click(function() { 
    $.ajax({ 
     url : "newComment", 
     type : "post", 
     data : { 
      "postId" : postId, 
      "newComment" : $("#newComment").val() 
     }, 
     success : function(data) { 
      console.log(data); 
      location.reload(); 
     }, 
     error : function() { 
      console.log("There was an error"); 
     } 
    }); 
}); 

和這裏的使用thymeleaf

<div id="newCommentForm"> 

     <form> 
      <div class="form-group"> 
       <textarea rows="2" id="newComment" placeholder="comment" class ="form-control" style="width: 520px;"></textarea> 
      </div> 
      <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" /> 
      <input type="submit" value="Comment" id="submit" class="btn btn-info" /> 
     </form> 

    </div> 

我的HTML如果任何人都可以看到我在做什麼錯了,讓我知道這將是非常感謝,提前。

回答

2

首先,你必須聲明在$(document).ready(function(){});點擊監聽器,否則之前存在的DOM元素的這部分代碼運行,因此他們不打電話給你的點擊功能。

修復此問題後,您將看到表單將執行其默認操作(與您現在正在使用的操作相同)。對於這一點,你必須避免你的提交按鈕的默認操作:

$(document).ready(function(){ 
    $("#submit").on("click", function(ev) { 
     ev.preventDefault(); 

     ... 

    }); 
}); 

個人而言,我喜歡on("click", ...)更多,但你的方式也能發揮作用。 希望它有幫助。

+0

工作完美,謝謝! – dochsner

1

表單是空白還是頁面空白?

您不是阻止HTML表單提交,所以表單正在提交,這就是爲什麼值在URL中。

嘗試:

所有的
$("#submit").click(function(e) { 

    e.preventDefault() 

    // ajax code here 

});