您是否将令牌 JS 添加到 Datatables 启动 JS 文件中?django-datatables 只是创建正确的 JSON 字符串。启动 cookie 是不同的。
我为此奋斗了一段时间,但我缺少的部分是我必须获取并设置 cookie:
// 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');
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);
}
}
});
这是上面我设置数据表参数的地方,例如:
let table = $('#datatables').DataTable({
"processing": true,
"serverSide": true,
stateSave: true,
"ajax": {
...........