我對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如果任何人都可以看到我在做什麼錯了,讓我知道這將是非常感謝,提前。
工作完美,謝謝! – dochsner