![](/img/trans.png)
[英]Ajax from php DataTables warning:table id=example - Invalid JSON response
[英]DataTables warning: invalid JSON response when there are no records in the table. Also added empty array but records are not displaying
我正在使用CodeIgniter和bootstrap数据表来显示数据库中的记录。
当表中没有可用记录时,我收到错误。
DataTables警告:table id = employee-List - 无效的JSON响应。 有关此错误的更多信息,请参阅http://datatables.net/tn/1
当表中可用时,将显示记录。
( 注意 :如果我在模型中添加了0数组的空数组,那么我的错误就会消失,但是数据库中没有显示记录。)
我试图在SO上找到解决方案,但没有一个解决方案适合我。 任何人都可以帮我解决我的代码问题吗?
我的代码是,
脚本
$('#employee-List').DataTable({
language: {
sLengthMenu: "Show _MENU_", // remove entries text
searchPlaceholder: "Search",
emptyTable: "No record found",
search: ""
},
"ordering": false, // remove sorting effect from header
"processing": true,
"serverSide": true,
"scrollX": true,
"bInfo": false,
"pageLength": 10,
"ajax": {
"url": baseUrl + "/Employee_control/fetch_employeeList",
"type": "POST"
},
"columns": [{
"data": "id",
"className": "reg_bg"
},
{
"data": "name"
},
{
"data": "email"
},
{
"data": "mobileno"
},
{
"data": "emp_id"
},
{
"data": "address"
},
{
"data": "action"
}
]
});
调节器
public function fetch_employeeList(){
$order_list=$this->Employee_model->fetch_employeeList();
// Datatables Variables
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$data['draw'] = 1;
$data['recordsTotal'] = count($order_list);
$data['recordsFiltered'] = count($order_list);
foreach ($order_list as $key => $row)
{
$action='<a href="" class="action-btn action-btn-border">View</a><a href="" class="action-btn action-btn-red-bg">Archive</a>';
$arr_result = array(
"id" =>$row->id,
"name" => $row->firstname." ".$row->middlename." ".$row->lastname,
"email" => $row->email_id,
"mobileno" => $row->mobileno,
"emp_id" => $row->employee_id,
"address" => $row->address,
"action" => $action
);
$data['data'][] = $arr_result;
}
//print_r($arr_result);
echo json_encode($data);
exit;
}
模型
public function fetch_employeeList(){
$this->db->select('*');
$this->db->from('tbl_employee');
$query = $this->db->get();
$result = $query->result();
if($result)
{
return $result;
}
else{
return []; //I added empty array instated of 0. Using this my error goes of but records are not displaying from the database.
}
}
问题是控制器返回的JSON响应需要始终包含名为data
的属性,以及在控制器中编写代码的方式,如果有结果,则只在响应数组中设置data
属性。
在你的控制器中,你需要将$data['data']
默认$data['data']
一个空数组,如下所示:
$data['draw'] = 1;
$data['recordsTotal'] = count($order_list);
$data['recordsFiltered'] = count($order_list);
$data['data'] = []; // add this line in controller
有关更多信息,请参阅服务器端处理的DataTables手册 (向下滚动到“返回数据”部分)
更新
在模型方法中,应该总是返回一个数组,而不是在没有结果时返回0
。 查看codeigniter的文档,如果没有结果, $query->getResult()
将返回一个空数组,因此您可以将模型方法更新为:
public function fetch_employeeList(){
$this->db->select('*');
$this->db->from('tbl_employee');
$query = $this->db->get();
return $query->result();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.