2013-01-16 29 views
0

我最近發佈了一個類似的問題。我在我的django應用程序中使用$ post jquery表單時遇到問題。它顯示一個403錯誤。

在我的previous thread,提供的答案,我縮小了可能的錯誤,並幫助我找到thread與類似的問題。

該線程的作者與我有同樣的問題。但是,投票數最多的答案對我來說不起作用。相反,做一個是這個:

//Everything works if I add the 
//"csrfmiddlewaretoken: '{{ csrf_token }}'" 
//in the data sent to the server. 

function test_post(){ 
    $.post("/xhr_test/", { 
     name: "Monty", 
     food: "Spam", 
     csrfmiddlewaretoken: '{{ csrf_token }}' 
    }, 
     function(data) { 
      alert(data); 
     } 

); 
}; 

雖然它的工作原理,我不喜歡這樣的解決方案,因爲我不得不說,「csrfmiddlewaretoken」添加到所有我送的字符串。

我想了解爲什麼最受讚譽的解決方案不適合我,因爲我認爲它是一個更優雅的解決方案。也就是說,加入這行代碼:

$.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')); 
     } 
    } 
}); 

我認爲這是一些與 「((/^HTTP:!。* /測試(settings.url)」 的部分可能需要更改。事有,但不知道是什麼。

+0

什麼是你的jQuery版本? – ustun

回答

0

首先,確保你的cookies啓用,這是因爲在這種方法中,csrftoken從cookie值拍攝,而不是從模板。

然後,嘗試粘貼代碼爲Chrome開發控制檯中的get_cookie函數,然後嘗試getCookie('csrftoken')。

如果它返回一個csrftoken,那麼cookie就在那裏。

接下來,您需要確保在那裏調用了ajaxSetup的代碼。把debugger聲明這樣前行:

debugger 
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { 

和單步執行代碼,看看它是否正確地設置了頭。

在官方文檔中嘗試使用它可能是個好主意。

相關問題