在我的代码中,Ajax第一次完美运行,但是当页面第二次加载ajax时它无法工作我第二次收到CSRF 403错误。
这是我的控制器:
$csrf_name = $this->security->get_csrf_token_name();
$csrf_hash = $this->security->get_csrf_hash();
$output = array("draw" => $draw,"recordsTotal" => $total_records,"recordsFiltered" => $total_records,"data" => $data, $csrf_name => $csrf_hash);
echo json_encode($output);
exit();
这是s JS:
$(document).ready(function() {
var csrf = jQuery('#csrf_hash').val();
$.fn.dataTable.moment('DD/MM/YYYY');
$('#messages').DataTable({
responsive: true,
iDisplayLength: 50,
"processing": true,
"serverSide": true,
"ajax": {
url : "<?php echo site_url("iot_lora/iot_lora_datatable_ajax") ?>",
type : 'POST',
"data": function(d) {
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
}
},
"fnDrawCallback" : function(response) {
var new_csrf = '<?php echo $this->security->get_csrf_hash(); ?>';
//alert(new_csrf);
//$("#csrf_hash").val("");
},
});
});
我的ajax设置:
$(function($) {
$.ajaxSetup({
data: {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
});
});
希望它会对你有所帮助。
在header.php文件中添加以下代码。
<meta name="csrf-token" content="{{ csrf_token() }}">
比在ajax的标题中添加X-CSRF-TOKEN。
$.ajax({
url : "URL",
type : "POST/GET",
dataType : "JSON",
data : $("#FORMDATA").serialize(),
headers : {"X-CSRF-TOKEN" : $('meta[name="csrf-token"]').attr('content')},
success : function (res){
},
error : function (err){
}
});
<meta name="csrf-token" content="{{ csrf_token() }}">
AND WRITE JQUERY CODE OUTSIDE DOCUMENT.READY FUNCTION
var csrf = jQuery('#csrf_hash').val();
$.fn.dataTable.moment('DD/MM/YYYY');
$('#messages').DataTable({
responsive: true,
iDisplayLength: 50,
"processing": true,
"serverSide": true,
"ajax": {
url : "<?php echo site_url("iot_lora/iot_lora_datatable_ajax") ?>",
type : 'POST',
"data": function(d) {
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
}
},
"fnDrawCallback" : function(response) {
var new_csrf = '<?php echo $this->security->get_csrf_hash(); ?>';
//alert(new_csrf);
//$("#csrf_hash").val("");
},
});