带有jquery的CSRF和django 1.3中的$ .post

tmp*_*ick 6 django jquery django-csrf

在django 1.3中,你现在必须使用csrf甚至是ajax.我使用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");

});
Run Code Online (Sandbox Code Playgroud)

应该说javascript不在模板中,而是在静态文件中.最好将它放在模板中,以便我可以使用{{ csrf_token }}

提前致谢!

小智 7

将此代码放在函数前面.它将照顾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'));
    }
});
Run Code Online (Sandbox Code Playgroud)