jQuery:为Django设置CSRF令牌无法正常工作

day*_*mer 2 django jquery csrf

我的jQuery功能看起来像

$(function() {
    // activate "New" buttons if input is not empty
    $('form input[type="text"]').live('keyup', function() {
        var val = $.trim(this.value);
        $(this).next("button").prop('disabled', val.length === 0);
    });

    $("body").on("submit","form",function(e){
        // do not submit the form
        e.preventDefault();

        // handle everything yourself
        var $form = $(this);
        var title = $form.closest('.video-detail').find('.title').text();
        var entryTitle = $form.find('.input-small').val();
        console.debug(title);
        console.debug(entryTitle);  

        $.ajaxSetup({ 
             beforeSend: function(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'));
                 }
             } 
        }); 

        // send the data to the server using .ajax() or .post()
        $.ajax({
            type: 'POST',
            url: 'addVideo',
            data: {
                video_title: title,
                csrfmiddlewaretoken: '{{ csrf_token }}'
                },
        }).done(function(){
            alert('done');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

这是基于回答Django CSRF检查失败的Ajax POST请求

我的html样子

<form class="new-playlist form-inline" onclick="event.stopPropagation()">{% csrf_token %}
    <input type="text" class="input-small">
    <button class="btn btn-danger create-playlist-button" type="submit" disabled="disabled">New</button>
</form>
Run Code Online (Sandbox Code Playgroud)

当我在Firefox中调试代码时,我将post值视为

csrfmiddlewaretoken {{ csrf_token }}
video_title The Who - Who Are You?
Run Code Online (Sandbox Code Playgroud)

我如何填充{{ csrf_token }}价值?

谢谢

woo*_*hoo 9

在我的情况下,我有一个模板,其中我不想有一个<form></form>元素.但是我仍然希望使用jQuery来发出AJAX POST请求.

我有403错误,因为CSRF cookie为null,即使我遵循了django文档(https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/).解决方案在同一页面,提到ensure_csrf_cookie装饰器.

当我在我的顶部添加这个时,我的CSRF cookie确实已经设置好了views.py:

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
Run Code Online (Sandbox Code Playgroud)

此外,请注意,在这种情况下,您不需要标记/模板中的DOM元素:{% csrf_token %}