【问题标题】:Jquery Ajax form not submitting and url is showing csrf tokenJquery Ajax 表单未提交且 url 显示 csrf 令牌
【发布时间】:2016-02-24 07:39:16
【问题描述】:

我是 Ajax 的新手,我正在尝试使用 jquery、ajax 和 thymeleaf 提交表单以获取视图。我知道 post url 有效,因为如果我只是告诉 ajax 在页面加载后立即提交表单中的任何内容都可以毫无问题地提交到数据库,但是如果我尝试使用提交按钮进行操作,那么表单变为空白,并且 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>

如果有人能看到我做错了什么并告诉我,那就太好了,在此先感谢。

【问题讨论】:

    标签: jquery ajax csrf thymeleaf


    【解决方案1】:

    首先,您必须在$(document).ready(function(){}); 中声明您的点击监听器,否则这部分代码会在您的 DOM 元素存在之前运行,因此它们不会调用您的点击函数。

    修复此问题后,您将看到表单将执行其默认操作(与您现在遇到的相同)。为此,您必须阻止提交按钮的默认操作:

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

    我个人更喜欢on("click", ...),但你的方式也可以。 希望对您有所帮助。

    【讨论】:

      【解决方案2】:

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

      您并没有阻止 HTML 表单提交,所以表单正在提交,这就是值在 URL 中的原因。

      试试:

      $("#submit").click(function(e) {
      
          e.preventDefault()
      
          // ajax code here
      
      });
      

      【讨论】:

        猜你喜欢
        • 2016-12-08
        • 1970-01-01
        • 2019-07-28
        • 2011-05-08
        • 2016-07-04
        • 1970-01-01
        • 2014-06-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多