如文档中所述,最好从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'时,它可以工作。 –