我对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