如文檔中所述,最好從cookie中獲取CSRF令牌。
// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
然後將它加入AJAX標題:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
這些簡單的後寫你的AJAX請求。 CSRF標題將自動添加。
你的情況:
$.ajax({
url: '/api/v1/order/' + orderid + '/',
type: 'PUT',
data: {}
});
查閱,https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax
我通常使用jQuery的'序列化()'後我數據到一個視圖。我真的不知道,但我想知道是否讓csrf令牌序列化有所作爲。 –
該代碼在哪裏?您應該參考[非常全面的文檔](https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax)來管理使用Ajax的CSRF,而不是引用「許多答案」。 –
使用'POST'時,它可以工作。 –