首页 > 解决方案 > Django:如何在使用 ajax 之前添加 csrf 令牌

问题描述

我正在我的项目中添加评论功能。我正在使用 ajax 使其动态化,这样当用户单击评论提交按钮时,它将动态添加到评论部分而无需刷新页面。但问题是,当使用 ajax 在表单前面添加时,我无法像这样添加 csrf 令牌

{% csrf_token %}

在表单中,因为 ajax 不会理解它并将其作为文本。

function getids(postid){
console.log(postid)
$(postformid).one('submit', function(event){
      event.preventDefault();
      console.log(event)
      console.log("form submitted!")  // sanity check
      create_comment(posted);
    });
}

// AJAX for posting
function create_comment(postid) {
    console.log("create comment is working!") // sanity check
    console.log(postid)
    console.log(talkid)
    $.ajax({
        url : "create_comment/"+postid, // the endpoint
        type : "POST", // http method
        data : { the_comment : $(cmtext).val() }, // data sent with the post request

        // handle a successful response
        success : function(json) {
            $(cmtext).val(''); // remove the value from the input
            console.log(json); // log the returned json to the console
            $(talkid).prepend(
              "<div class='col-1 p-0'><form' id=upvote' method='POST'>{%"csrf_token"%}<button 
              class='btn btn-md btn-outline-danger btn- 
              block p-auto' id='btnid' onclick='---' type='submit'></button></form></div>");
              console.log("success"); // sanity check
        },

    // handle a non-successful response
        error : function(xhr,errmsg,err) {
        }
    });
};

在这里假装我的表格

<div class="row m-0" id="talk{{post.id}}"></div>

还有其他方法吗?

标签: djangoajaxdjango-formsajaxform

解决方案


利用

{% csrf_token %}

就在模板内的表单标签之前。


推荐阅读