使用jQuery实现DataTables服务端分页时数据不渲染到表格问题
问题原因及解决步骤
1. 控制器接口返回内容不符合要求
你当前fetch_user方法在输出JSON后又加载了视图,导致最终返回给前端的内容是JSON字符串 + 视图HTML代码,DataTables无法解析为合法JSON,所以一直停在Processing状态。
修改控制器代码,在echo json_encode($output);后终止程序,删除多余的加载视图逻辑:
function fetch_user(){ $this->load->model("contacts_model"); $fetch_data = $this->contacts_model->make_datatables(); $data = array(); foreach($fetch_data as $row) { $sub_array = array(); $sub_array[] = $row->firstname; $sub_array[] = $row->lastname; $data[] = $sub_array; } $output = array( "draw" => intval($_GET["draw"]), "recordsTotal" => $this->contacts_model->get_all_data(), "recordsFiltered" => $this->contacts_model->get_filtered_data(), "data" => $data ); echo json_encode($output); // 终止输出,删除原有加载视图的代码 exit; }
2. 前端DataTables配置列索引错误
你的表格只有2列,列索引对应为0(First Name)、1(Last Name),但columnDefs里写了targets:[0, 3, 4],引用了不存在的3、4列,会触发JS异常导致渲染失败,修改为对应实际存在的列即可:
"columnDefs":[ { "targets":[0], // 仅给存在的列设置不可排序,不需要该配置也可直接删除 "orderable":false, }, ],
3. 访问路径错误
你直接访问http://localhost/contacts/fetch_user本身就是接口地址,返回JSON是正常行为,你应该访问存放表格的视图页面对应的路由,而不是直接访问数据接口地址。
内容的提问来源于stack exchange,提问作者H2O
相关产品推荐
相关产品推荐

