2012-08-04 54 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 %}