数据表警告:表 id=users_list - JSON 响应无效.有关此错误的详细信息,请参阅 http://data



我正在根据活动-非活动状态从用户表中获取数据,之后使用 foreach 循环数据应使用数据表显示,但出现错误

数据表警告:表 id=users_list - 无效的 JSON 响应

所以我的要求是

1) Show all data in the data table
2) per page 5 records
3) Default search box of a data table
4) Pagination of a data table

以下是我的代码,但这对我不起作用 在索引中.php文件下拉列表,并基于onchange事件ajax调用ajax控制器中的users_list方法。

In index.php  file drop-down list with ajax call request

<select class="custom-select" onchange="get_users(this.value)">
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
<div class="show_data"></div>
<script>
function get_users(status){
$.ajax({
type:'POST',
url:'<?php echo SITE_URL . 'ajax/users_list'; ?>',
data:{ status:status},        
success: function(data)
{        
$(".show_data").html(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Failed');
}
});
}
</script>

在控制器 Ajax 中.php

function users_list(){
$status=$this->input->post('status');   //active  or inactive 
$data['users']=$this->db->where('status',$status)->get('users')->result();
$this->load->view('view_assets',$data); 
}

在view_assets.php文件中

<table id="display_userinfo">
<thead>
<tr class="bg-light">
<th>user id</th>
<th>user name</th>
<th>Mobile no</th>
</tr>
</thead>
<?php foreach ($users as $user) { ?>
<tbody>
<tr>
<td><?= $user->id ?></td>
<td><?= $user->name ?></td>
<td><?= $user->mobile ?></td>
</tr>
<?php } ?>
</tbody>
<script>
$('#display_userinfo').DataTable({
"processing": true,
"serverSide": true,
});
</script>

JavaScript

您已在调用DataTable()时将ServerSide设置为 true。但您已经创建了表。更改此设置:

$('#display_userinfo').DataTable({
"processing": true, //Optional, only useful for *large* tables
//"serverSide": true, //REMOVE THIS
});

从他们的文档中:

默认情况下,DataTables 在客户端处理模式下运行,但可以使用此选项切换到服务器端处理模式。服务器端处理在处理大型数据集(通常为>50'000 条记录)时很有用,因为这意味着数据库引擎可用于执行排序等计算 - 现代数据库引擎高度优化的操作,允许使用具有大量数据集(数百万行)的 DataTables。

仅当您计划提供 JSONDataTable()时才应使用ServerSide。否则,您可以在没有ServerSide标志的情况下运行DataTable(),它会将您的 HTML 转换为其格式。

如果您重新调整后端,您仍然可以使用ServerSide,但可能不是必需的。下面是一个入门示例:

$('#display_userinfo').dataTable( {
"serverSide": true, //Here it's necessary
"ajax": {
"url": '<?php echo SITE_URL . 'ajax/users_list'; ?>',
"data": {}
}
});

.HTML

您还犯了一个小的标记错误,该错误可能会也可能不会对 DataTable 产生影响。更改以下内容:

<tbody> <!-- This needs to be BEFORE the foreach() loop -->
<?php foreach ($users as $user) { ?>
<tr>
<td><?= (int)$user->id ?></td>
<td><?= htmlspecialchars((string)$user->name) ?></td>
<td><?= htmlspecialchars((string)$user->mobile) ?></td>
</tr>
<?php } ?>
</tbody> <!-- Correctly placed *AFTER* the foreach() loop -->

最新更新