django - 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>
还有其他方法吗?
解决方案
利用
{% csrf_token %}
就在模板内的表单标签之前。
推荐阅读
- python - 打印功能重要性百分比
- django - Django jsonfield,是否可以使用json数组值长度进行过滤?
- python - 错误:找不到满足 pyautogui 要求的版本(来自版本:无)
- electron - 有没有办法在 Electron 应用程序包根目录中复制或创建文件夹?
- java - Springdoc 将安全性指定为打开
- java - 如何使用 bufferedreader 捕获 csv 文件中的字段值
- javascript - 如何使用现代 FileApi 在本地 fs 中创建文件?
- xamarin - Xamarin 在 Andriod 设备上使用黑色背景和白色二维码形成 Zxing 扫描问题
- linux - 根据命令行中同一行中的单词的条件更改另一个单词?
- c# - C#:Random.NextDouble 方法停止应用程序