jQuery:为 Django 设置 CSRF token 不起作用

标签 jquery django 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');
        });
    });
});

这是基于答案 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 中调试代码时,我看到帖子值为

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

如何填充 {{ csrf_token }} 值?

谢谢

最佳答案

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

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

当我将其添加到我的 views.py 顶部时,我的 CSRF cookie 确实被设置了:

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

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

关于jQuery:为 Django 设置 CSRF token 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11812694/

相关文章:

django - pop()' 在 Django Rest FrameWork 中有什么作用?

rest - 防止 CSRF 和 XSS(哈希 + 加密)

jquery - ASP.Net 服务器控制、回发架构在当前的 Web 2.0 世界中失败了吗?

javascript - 如果未选中复选框则添加属性

django - 什么是防止 memcached CacheKeyWarning 的好/结构化方法?

python - 返回浮点(值)值错误: could not convert string to float in Django models

javascript - 无法将 CSRF token 添加到 Django POST 请求的 XMLhttpRequest

javascript - 通过 &lt;script&gt; 标签加载到网页中的 JavaScript 文件的源可以被该页面中的其他 JavaScript 读取吗?

javascript - removeAttr() 和 remove() 不起作用

javascript - 无法在 Django 中使用 jquery 禁用按钮