我对Ajax有点陌生,我正在尝试为视图提交一个使用jquery、ajax和thymeleaf的表单。我知道post url是有效的,因为如果我告诉ajax在页面加载表单中的任何内容后立即提交到数据库中,没有问题,但是如果我尝试使用submit按钮来完成它,则表单变为空,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>如果有人能看出我做错了什么,并让我知道这将是很好的,谢谢提前。
发布于 2015-11-21 23:58:46
首先,必须在$(document).ready(function(){});中声明单击监听器,否则在DOM元素存在之前运行这部分代码,因此它们不会调用click函数。
在修复这个问题之后,您将看到表单将执行它的默认操作(就像您现在正在经历的一样)。为此,必须防止提交按钮的默认操作:
$(document).ready(function(){
$("#submit").on("click", function(ev) {
ev.preventDefault();
...
});
});就我个人而言,我更喜欢on("click", ...),但你的方式也会奏效。希望能帮上忙。
发布于 2015-11-21 23:58:34
表单是空白的还是页面是空白的?
您没有阻止HTML表单提交,因此正在提交表单,这就是为什么值在URL中的原因。
尝试:
$("#submit").click(function(e) {
e.preventDefault()
// ajax code here
});https://stackoverflow.com/questions/33850029
复制相似问题