儘管上述方法可用於AJAX POST請求,但有一些不便之處:您必須記住將CSRF令牌作爲POST數據傳遞給每個POST請求。出於這個原因,還有一種替代方法:在每個XMLHttpRequest上,將自定義X-CSRFToken標頭設置爲CSRF標記的值。這通常更容易,因爲許多javascript框架提供了允許在每個請求上設置標題的鉤子。
您需要通過一個AJAX調用發送CSRF令牌:
$.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'));
}
}
});
下面是引用鏈接,https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/#ajax
OK !!!!現在我明白了從cookie中發佈CRSF的興趣,而不是從模板的「{%crsf_token%}」 –