2

我的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');
        });
    });
});

这是基于答案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>

当我在 Firefox 中调试代码时,我看到 post 值为

csrfmiddlewaretoken {{ csrf_token }}
video_title The Who - Who Are You?

如何填充该{{ csrf_token }}值?

谢谢

4

2 回答 2

9

就我而言,我有一个模板,我不想在其中包含<form></form>元素。但我仍然想使用 jQuery 发出 AJAX POST 请求。

由于 CSRF cookie 为空,我得到了 403 错误,即使我遵循了 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

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

于 2013-07-10T01:43:00.320 回答
0

<input type="hidden" name="csrfmiddlewaretoken" value="SOME_TOKEN">

以上是django输出的标记。您想获取 SOME_TOKEN 的值。您将无法使用与 javascript 混合的 django 模板引擎来获取它,因为它已经被渲染到隐藏的输入中。

我会将我的内容包装{{ csrf_token }}在一个 span/div 中,然后使用 jquery 来定位该 span/div 并获取 span/div内的输入

于 2012-08-04T23:25:09.333 回答