django 1.3 中使用 jquery 和 $.post 进行 CSRF
在 django 1.3 中,即使使用 ajax,您现在也必须使用 csrf。 我使用 jquery,现在想将 csrf 令牌添加到 $.post 中。我该怎么做?我对 jquery 不是很熟练,所以最好有一个好的描述。
这是一个评级应用程序,当点击星星时就会发送帖子。 我已经看过 django 文档 但不明白在我的情况下该怎么做。我的代码如下:
$(function() {
$("#avg").children().not(":input").hide();
$("#rating-widget").children().not("select").hide();
$caption = $("<span/>");
$("#avg").stars({captionEl: $caption});
$("#rating-widget").stars({
inputType: "select",
cancelShow: false,
captionEl: $caption,
callback: function(ui, type, value){
--------------> $.post($("#rating-widget").attr("action"), {score: value}, function(data){
});
}
});
$caption.appendTo("#rating-widget");
});
应该说,javascript不在模板中,而是在静态文件中。 最好将其放入模板中,以便我可以使用 {{ csrf_token }}
提前致谢!
In django 1.3 you now have to use csrf even with ajax.
I use jquery and I now want to add the csrf token to the $.post. How can i do this? I am not very skilled in jquery so it would be nice with a good description.
It is a rating app and the post is send when a star is clicked.
I have seen the django docs but do not understand what to do in my situation. My code is below:
$(function() {
$("#avg").children().not(":input").hide();
$("#rating-widget").children().not("select").hide();
$caption = $("<span/>");
$("#avg").stars({captionEl: $caption});
$("#rating-widget").stars({
inputType: "select",
cancelShow: false,
captionEl: $caption,
callback: function(ui, type, value){
--------------> $.post($("#rating-widget").attr("action"), {score: value}, function(data){
});
}
});
$caption.appendTo("#rating-widget");
});
It should be said that the javascript is not in a template but in a static file.
Would it be best to put it in a template so I could use {{ csrf_token }}
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 django 文档中,您可以找到有关如何进行的简单描述在每个ajax请求中自动包含csrf令牌!
In the django documentation you can find a simple description on how to automatically include the csrf token in each ajax request!
您不必使用表格!只需创建一个绑定到“加星标”帖子的函数的新网址即可。例如
,如果您向该 url 发送请求,它将在您的数据库中找到该帖子,将该字段更改为“加星标”并向 ajax 返回响应。
然后你可以有一个成功时的回调函数,该函数将相应地更改 CSS(填充星号等)。这样,你就不用担心CSRF了。
但您可能会问,那么跨站点脚本攻击又如何呢?好吧,如果您使用带有 cookie 验证的用户身份验证,则不必担心这一点!啊啊,你就可以走了。
You don't have to use a form! Just create a new url that is bound to a function that "stars" posts. For example
Therefore, if you send a request to that url, it will find the post in your database, change the field to "starred" and return a response to ajax.
Then you can have a callback function on success that will change the CSS accordingly (fill in the star, or etc). This way, you don't have to worry about CSRF.
But you may ask, well what about cross-site-scripting attacks! Well, if you are using user authentication with cookie validation, you shouldn't have to worry about that! Aaaand you're good to go.
将此代码放在您的函数之前。它将处理 CSRF。
Place this code before your function. It will take care of CSRF.