2015-11-21 28 views
1

我对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如果任何人都可以看到我在做什么错了,让我知道这将是非常感谢,提前。

回答

2

首先,你必须声明在$(document).ready(function(){});点击监听器,否则之前存在的DOM元素的这部分代码运行,因此他们不打电话给你的点击功能。

修复此问题后,您将看到表单将执行其默认操作(与您现在正在使用的操作相同)。对于这一点,你必须避免你的提交按钮的默认操作:

$(document).ready(function(){ 
    $("#submit").on("click", function(ev) { 
     ev.preventDefault(); 

     ... 

    }); 
}); 

个人而言,我喜欢on("click", ...)更多,但你的方式也能发挥作用。 希望它有帮助。

+0

工作完美,谢谢! – dochsner

1

表单是空白还是页面空白?

您不是阻止HTML表单提交,所以表单正在提交,这就是为什么值在URL中。

尝试:

所有的
$("#submit").click(function(e) { 

    e.preventDefault() 

    // ajax code here 

});