django csrf在ajax POST(csrf cookie未设置,直到{{csrf}}使用) [英] Django csrf in ajax POST (csrf cookie not set until {{csrf}} used)
问题描述
我的django应用程序使用ajax将项目添加到购物车。 ajax请求方法是POST,并且通过js启用请求头:
My django application uses ajax to add an item to shopping cart. The ajax request method is POST, and i enable request header via js:
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
问题是,我不是从表单发送请求,而是使用按钮和onClick事件,所以我不在模板中使用{{csrf}}。所以,没有设置cookie,直到我访问另一个页面(例如,登录页面)。我应该使用一个表单(这不是一个很好的主意,因为我有一个页面上的许多项目,并与形成csrf令牌是为每个创建),或有一种方法设置csrf cookie手动,如果不是组?感谢。
The problem is, that i send request not from the form, but just using a button and onClick event, so i do not use a {{ csrf }} in the template. So, the cookie is not set, until i visit another page (for example, login page). Should i use a form (it is not a very good idea, because i have many items on one page, and form with csrf token is created for each one), or there is a way to set csrf cookie manually, if it is not set? Thanks.
推荐答案
您随时可以放置 {%csrf_token%}
隐藏表单字段在模板中的任何位置,如果cookie尚未设置,则通过名称选择它。
You can always just drop a {% csrf_token %}
hidden form field anywhere in your template and pick it up by name if the cookie isn't set yet. You don't have to put it inside a form tag to be valid HTML.
只需将逻辑更改为:
var csrftoken == getCookie('csrftoken') || $(":input[name='csrfmiddlewaretoken']").val();
这当然取决于 getCookie
。
这篇关于django csrf在ajax POST(csrf cookie未设置,直到{{csrf}}使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!