我正在使用CodeIgniter,我们启用了CSRF Protection,
$config['csrf_protection'] = TRUE;
我们使用了:
`<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">`
在表格提交及其工作正常中,
但是我的应用程序还使用DataTables获取使用Ajax的服务器数据,
var handleDataTable = function () {
var table = $('#my_table').DataTable({
"ajax": {
"url" : baseURL + "user/core/data/"+report_id,
"dataType" : "json",
"type" : "POST", // ajax source
},
});
}
显然这将显示" The action you have requested is not allowed.
"消息,
如何通过AJAX检索数据传递CSRF?
将其作为ajax函数中的标头传递:
var handleDataTable = function () {
var table = $('#my_table').DataTable({
"ajax": {
"url" : baseURL + "user/core/data/"+report_id,
"dataType" : "json",
"type" : "POST", // ajax source
"headers": {
'CSRFToken': TOKEN //replace by your name/value
}
},
});
如果您有很多AJAX请求,则应为所有请求设置一个全局标头:
$.ajaxSetup( {
headers: {
'CSRFToken': TOKEN //replace by your name/value
}
});
或发送名称/值对作为数据的一部分:
$('#myTable').DataTable( {
ajax: {
url: '...',
data: function ( d ) {
d.csrfName = csrfValue;
}
}
} );
源