我正在使用带有引导数据表的 CodeIgniter 来显示数据库中的记录。
当表中没有可用记录时出现错误。
DataTables warning: table id=employee-List - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
记录在表中可用时显示。
我试图在 SO 上找到解决方案,但没有一个解决方案适合我。有人可以帮助我解决我的代码有什么问题吗?
我尝试了@BlueWater86 的回答,错误消失了,但我的记录没有显示。
你能帮我解决这个问题吗?
我的代码是,
脚本
$('#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",
"dataSrc": ""
},
"columns": [{
"data": "id",
"className": "reg_bg"
},
{
"data": "name"
},
{
"data": "email"
},
{
"data": "mobileno"
},
{
"data": "emp_id"
},
{
"data": "address"
},
{
"data": "action"
}
]
});
Controller
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 0;
}
}
最佳答案
在静态类型语言中不会遇到这种问题。如果考虑 fetch_employeeList()
函数的接口(interface),它返回一个动态;有时是对象数组,有时是数字 0。
如果没有员工查询结果,应该返回一个空数组而不是数字0。
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 [];
}
}
关于javascript - 数据表警告 : invalid JSON response when there are no records in the table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56420466/