所以,我是新来的ajax,我试图使用ajax和jquery提交表单,我想我有服务器端逻辑都想通了,因为当我加载页面它会自动提交并且页面刷新速度非常快。空白表单将进入数据库,但其中有很多内容,因为页面会一直提交每次刷新。所以我认为我的服务器端正在工作,但我不知道要做什么来阻止它刷新,还要使用我在html表单中提交的提交按钮进行提交。我在我的html页面中使用了thymeleaf。Ajax自动提交和刷新页面
这是我的HTML表单,使用thymeleaf
<div id="newCommentForm">
<fieldset>
<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" class="btn btn-info" />
</fieldset>
</div>
这是我的jQuery和AJAX
<script th:inline="javascript">
/*<![CDATA[*/
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
<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>
我完全复制了代码,现在甚至没有尝试提交,甚至没有在控制台上显示“有错误”。 – dochsner
您是否将网址调整为正确的值,并确保该按钮的ID是正确的。 –
是啊,我所做的只是复制和粘贴你的代码,即使URL不正确,是否至少会给我一个错误? – dochsner