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 ie 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看起来像

 
{% csrf_token %}

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

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

如何填充{{ csrf_token }}值?

谢谢

在我的情况下,我有一个模板,我不希望有一个

元素。 但是我仍然希望使用jQuery来发出AJAX POST请求。

我有403错误,因为CSRF cookie为空,即使我遵循了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 %}

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

我将我的{{ csrf_token }}包装在span / div中,然后使用jquery来定位span / div并获取span / div中输入的值 。