2012-08-04 55 views
2
设立CSRF令牌

jQuery函数看起来像jQuery的:Django的不工作

$(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 }}值?

谢谢

+0

getCookie('csrftoken')'返回什么? – 2013-03-19 13:03:53

回答

0

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

以上是由Django的输出标记。你想获得SOME_TOKEN的价值。您将无法使用与javascript混合使用的django模板引擎来获取它,因为它已经呈现为隐藏的输入。

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

9

在我的情况下,我有一个模板,我不想有一个<form></form>元素。但我仍然想使用jQuery进行AJAX POST请求。

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

我CSRF饼干没有得到设定,当我加入这个在我views.py的顶部:

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

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