csrf_token未找到django ajax
<script>
function post(e) {
data = $("#form_add_post").serialize();
$.post("/post/", function(data) {
alert("posted");
});
return false;
}
function addPost(){
$(".matter").html("<form id='form_add_post' onsubmit='return post(event);'>{% csrf_token %} <table> <tr> <td class='heading'>Title: </td> <td class='box'><input type='text' name='title'></td> </tr> <tr> <td colspan='2'><textarea class='data' name='content'></textarea></td> </tr> </table> <input id='submitt1' type='submit'> </form>");
}
</script>
我正在尝试执行AJAX后调用。我也放置了csrf_token。我已经交叉检查了正在发送的数据。它显示了包括csrf_token在内的全部细节。
我的数据:csrf_token未找到django ajax
csrfmiddlewaretoken = foYqu9LrR25AomOmcFkaEicmN3CU2wcRNVg1gRPgl2F9XfL6IWerpbSK6TUKd4Ke &标题=计&含量= hhgj%3B%3Bhghjbjn
但我得到一个403错误显示
CSRF验证失败。请求中止。
尽量使请求这样
$.ajax({
type:form.attr('method'),
url:form.attr('action'),
data:form.serialize(),
success: function(){
...
}
});
完美工作。我可以知道我写的代码中存在什么问题。 – dharmista
按照Laravel Docs你应该增加CSRF令牌在Ajax的请求是这样的:
HTML代码:
<meta name="csrf-token" content="{{ csrf_token() }}">
JS代码:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
在Django的情况下 - 您需要将
{% csrf_token %}
模板 标记添加为Django模板中表单元素的子元素。看到这个 - Question
希望这有助于!
您正在致电$.post
错误。如果您在开发人员工具中查看请求,我想您会看到帖子数据为空。
第二个参数应该是请求数据,第三个参数是success
回调。
$.post("/post/",
data,
function (response_data) {
alert("posted");
}
);
一旦你已经修复了,the Django docs展示如何包括CSRF令牌作为Ajax请求头,所以你不必把它列入表单主体。
看看这个链接[https://docs.djangoproject.com/es/1.10/ref/csrf/#ajax](https:// docs.djangoproject.com/es/1.10/ref/csrf/#ajax) – jaime