【问题标题】:jQuery: setting up CSRF token for Django not workingjQuery:为 Django 设置 CSRF 令牌不起作用
【发布时间】:2012-08-02 12:05:47
【问题描述】:

我的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 check failing with an Ajax POST request

我的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 }} 值?

谢谢

【问题讨论】:

  • getCookie('csrftoken') 返回什么?

标签: jquery django csrf


【解决方案1】:

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

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

当我在views.py 顶部添加此内容时,我的 CSRF cookie 确实被设置了:

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie

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

【讨论】:

    【解决方案2】:

    &lt;input type="hidden" name="csrfmiddlewaretoken" value="SOME_TOKEN"&gt;

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-26
      • 2015-05-07
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 2021-07-14
      相关资源
      最近更新 更多