django 1.3 中使用 jquery 和 $.post 进行 CSRF

发布于 2024-11-10 18:31:40 字数 1045 浏览 4 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌化 2024-11-17 18:31:42

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!

捎一片雪花 2024-11-17 18:31:42

您不必使用表格!只需创建一个绑定到“加星标”帖子的函数的新网址即可。例如

(r'^myapp/star-post/(?P<post_id>.*)/

,如果您向该 url 发送请求,它将在您的数据库中找到该帖子,将该字段更改为“加星标”并向 ajax 返回响应。

然后你可以有一个成功时的回调函数,该函数将相应地更改 CSS(填充星号等)。这样,你就不用担心CSRF了。

但您可能会问,那么跨站点脚本攻击又如何呢?好吧,如果您使用带有 cookie 验证的用户身份验证,则不必担心这一点!啊啊,你就可以走了。

,'myapp.views.myview')

,如果您向该 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

(r'^myapp/star-post/(?P<post_id>.*)/

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.

,'myapp.views.myview')

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.

电影里的梦 2024-11-17 18:31:41

将此代码放在您的函数之前。它将处理 CSRF。

$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

Place this code before your function. It will take care of CSRF.

$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文