CodeIgniter 3结合Datatables与Ajax实现数据库数据展示求助
解决CodeIgniter 3 + DataTables服务器端数据展示问题
我看了你的代码,发现几个关键细节需要调整,这样才能让DataTables和CI3顺利交互并正确展示数据:
1. 修复控制器的JSON返回格式
DataTables服务器端模式要求返回固定结构的JSON,必须包含draw、recordsTotal、recordsFiltered和data这几个核心字段——你的原代码只返回了数据列表,这会导致DataTables无法解析响应。同时CSRF的处理也需要优化:
public function getData() { // 确保加载模型,CI3会自动验证POST请求的CSRF令牌(需在config中开启CSRF) $this->load->model('main_model'); // 获取DataTables传递的服务器端参数 $draw = intval($this->input->post('draw')); $start = intval($this->input->post('start')); $length = intval($this->input->post('length')); $searchKeyword = $this->input->post('search')['value']; // 调用模型获取三类数据:总记录数、过滤后记录数、分页结果 $totalRecords = $this->main_model->get_total_count(); $filteredRecords = $this->main_model->get_filtered_count($searchKeyword); $tableData = $this->main_model->get_paginated_data($start, $length, $searchKeyword); // 构造DataTables要求的JSON结构 $response = array( "draw" => $draw, "recordsTotal" => $totalRecords, "recordsFiltered" => $filteredRecords, "data" => array() ); if (!empty($tableData)) { foreach ($tableData as $row) { $response['data'][] = array( $row->name, $row->last_name ); } } // 返回新的CSRF令牌,避免重复提交问题 $response[$this->security->get_csrf_token_name()] = $this->security->get_csrf_hash(); echo json_encode($response); }
2. 完善模型的数据库操作逻辑
你的原模型data()方法没有处理分页、搜索等服务器端参数,这里拆分成三个方法更清晰:
class Main_model extends CI_Model { // 获取表中总记录数 public function get_total_count() { return $this->db->count_all('your_table_name'); // 替换成你的实际表名 } // 获取搜索过滤后的记录数 public function get_filtered_count($keyword) { if (!empty($keyword)) { $this->db->like('name', $keyword); $this->db->or_like('last_name', $keyword); } return $this->db->count_all_results('your_table_name'); // 替换成你的实际表名 } // 获取分页后的数据集 public function get_paginated_data($start, $length, $keyword) { if (!empty($keyword)) { $this->db->like('name', $keyword); $this->db->or_like('last_name', $keyword); } $this->db->limit($length, $start); return $this->db->get('your_table_name')->result(); // 替换成你的实际表名 } }
3. 优化前端JS的CSRF令牌处理
CI3的CSRF令牌会在每次请求后更新,硬编码令牌容易导致验证失败,建议动态读取并更新:
首先在视图页面添加一个隐藏的CSRF令牌字段(可放在表格上方任意位置):
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
然后修改JS代码,自动处理令牌的传递和更新:
$(document).ready(function(){ $('#myTable').DataTable( { "processing": true, "serverSide": true, "order": [], // 禁用默认排序规则 "ajax": { "url": '<?= base_url('main/getData');?>', "type": "POST", "data": function(d) { // 将CSRF令牌加入请求参数 const csrfName = $('input[name="<?php echo $this->security->get_csrf_token_name(); ?>"]').attr('name'); d[csrfName] = $('input[name="<?php echo $this->security->get_csrf_token_name(); ?>"]').val(); }, "dataSrc": function(json) { // 更新页面中的CSRF令牌为后端返回的新令牌 const csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>'; $('input[name="' + csrfName + '"]').val(json[csrfName]); return json.data; } } }); });
4. 完善视图表格结构
确保表格包含空的tbody,DataTables会自动填充数据:
<table id="myTable" class="display" style="width:100%"> <thead> <tr> <th>Name</th> <th>Last_name</th> </tr> </thead> <tbody></tbody> <!-- 新增空tbody --> </table>
额外注意事项
- 确保已引入DataTables的CSS和JS文件(可使用CDN):
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css"> <script type="text/javascript" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script> - 检查CI3配置文件
config.php中CSRF是否开启:$config['csrf_protection'] = TRUE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200;
调整完成后,你的DataTables应该就能正常从CI3后端获取数据并展示了。
内容的提问来源于stack exchange,提问作者user9855854
相关产品推荐
相关产品推荐

