所以,我是新来的ajax,我试图使用ajax和jquery提交表单,我想我有服务器端逻辑都想通了,因为当我加载页面它会自动提交并且页面刷新速度非常快。空白表单将进入数据库,但其中有很多内容,因为页面会一直提交每次刷新。所以我认为我的服务器端正在工作,但我不知道要做什么来阻止它刷新,还要使用我在html表单中提交的提交按钮进行提交。我在我的html页面中使用了thymeleaf。Ajax自动提交和刷新页面
这是我的HTML表单,使用thymeleaf
这是我的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);
});
$(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");
}
});
});
/*]]>*/
在此先感谢。
UPDATE
所以现在当我提交表单的页面刷新和URL做一些奇怪的事情,并显示CSRF令牌,并没有提交到数据库中的数据。因此,当我提交http://localhost:8080/viewCourse/post/1?_csrf=abefbd5b-392e-4c41-9d66-d66616fc4cc7时,如果我取消了所做的更改并将其放回到刷新循环中,并且如果我可以在表单中获取任何文本,在页面刷新之前它实际上会提交到数据库,所以我认为这意味着我有一个有效的网址,因为它有点作品。我真的不知道是什么原因造成的,但表单似乎没有提交正确的信息,只有csrf标记。这里是我的最新的jQuery,Ajax和HTML
jQuery的 //
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