【发布时间】:2016-02-24 07:39:16
【问题描述】:
我是 Ajax 的新手,我正在尝试使用 jquery、ajax 和 thymeleaf 提交表单以获取视图。我知道 post url 有效,因为如果我只是告诉 ajax 在页面加载后立即提交表单中的任何内容都可以毫无问题地提交到数据库,但是如果我尝试使用提交按钮进行操作,那么表单变为空白,并且 url 更改为类似 http://localhost:8080/viewCourse/post/1?_csrf=d512fb5c-08e5-4373-895e-1297b0c35a4b 的内容,并且没有任何内容进入数据库,但控制台中也没有错误,所以我不确定发生了什么。
这是我的 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");
}
});
});
这是我使用百里香的 html
<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>
如果有人能看到我做错了什么并告诉我,那就太好了,在此先感谢。
【问题讨论】:
标签: jquery ajax csrf thymeleaf