无效的 JSON 响应:引导数据表

Posted

技术标签:

【中文标题】无效的 JSON 响应:引导数据表【英文标题】:Invalid JSON response: Bootstrap datatables 【发布时间】:2016-10-31 16:04:14 【问题描述】:

我在这里有一个使用 codeigniter 与数据库连接的数据表。这里的问题是我的数据表没有显示输出。如果通过 ajax 的数据发送到我的控制器,我会检查开发人员工具/网络。任何帮助将不胜感激。

我的控制器

    class Person extends MY_Controller 

    public function __construct()
    
        parent::__construct();
        $this->load->model('person_model','person');
    

    public function index()
    
        $this->load->helper('url');
        $this->data['title'] = 'Division'; 
        $this->middle = 'person_view'; // its your view name, change for as per requirement.
        $this->layout();
    

    public function ajax_list()
    
        $list = $this->person->get_datatables();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $division) 
            $no++;
            $row = array();
            $row[] = $division->division_code;
            $row[] = $division->division_name;
            $row[] = $division->division_acro;

            //add html for action
            $row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_person('."'".$division->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
                  <a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_person('."'".$division->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';

            $data[] = $row;
        

        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->person->count_all(),
                        "recordsFiltered" => $this->person->count_filtered(),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    

我的模特

class Person_model extends CI_Model 

    var $table = 'division';
    var $column_order = array('division_code','division_name','division_acro','division_date',null); //set column field database for datatable orderable
    var $column_search = array('division_code','division_name','division_acro'); //set column field database for datatable searchable just firstname , lastname , address are searchable
    var $order = array('id' => 'desc'); // default order 

    public function __construct()
    
        parent::__construct();
        $this->load->database();
    

    private function _get_datatables_query()
    

        $this->db->from($this->table);

        $i = 0;

        foreach ($this->column_search as $item) // loop column 
        
            if($_POST['search']['value']) // if datatable send POST for search
            

                if($i===0) // first loop
                
                    $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
                    $this->db->like($item, $_POST['search']['value']);
                
                else
                
                    $this->db->or_like($item, $_POST['search']['value']);
                

                if(count($this->column_search) - 1 == $i) //last loop
                    $this->db->group_end(); //close bracket
            
            $i++;
        

        if(isset($_POST['order'])) // here order processing
        
            $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
         
        else if(isset($this->order))
        
            $order = $this->order;
            $this->db->order_by(key($order), $order[key($order)]);
        
    

    function get_datatables()
    
        $this->_get_datatables_query();
        if($_POST['length'] != -1)
        $this->db->limit($_POST['length'], $_POST['start']);
        $query = $this->db->get();
        return $query->result();
    

    function count_filtered()
    
        $this->_get_datatables_query();
        $query = $this->db->get();
        return $query->num_rows();
    

    public function count_all()
    
        $this->db->from($this->table);
        return $this->db->count_all_results();
    

我的视图脚本

<script type="text/javascript">

var save_method; //for save method string
var table;

$(document).ready(function() 

    //datatables
    table = $('#table').DataTable( 

        "processing": true, //Feature control the processing indicator.
        "serverSide": true, //Feature control DataTables' server-side processing mode.
        "order": [], //Initial no order.

        // Load data for the table's content from an Ajax source
        "ajax": 
            "url": "<?php echo  ('person/ajax_list')?>",
            "type": "POST"
        ,

        //Set column definition initialisation properties.
        "columnDefs": [
         
            "targets": [ -1 ], //last column
            "orderable": false, //set not orderable
        ,
        ],

    );
);
</script>

【问题讨论】:

您在 ajax 调用中得到什么响应? 在开发者工具的网络选项卡中查看响应。控制器可能在 JSON 之前或之后打印某些内容,您需要修复它。 @RajJagani 我就像这样在我的数据库中获取数据。 - "draw":"1","re​​cordsTotal":43,"recordsFiltered":43,"data":[["div-043","Division","D"," 等等。 @Barmar 只是想问问。我正在使用 codeigniter my_controller。我有我的布局资产。如果是触发错误的问题之一?我应该在我的路由器或自动加载等中更改什么。 您使用的是哪个数据表版本?我有 Datatable 版本 1.10.9 的完整代码。如果您使用的是 1.X.X,那么我可以输入该代码。 【参考方案1】:

试试下面的代码

在控制器中

public function datatable()
    
        if($this->input->is_ajax_request()) 
            $start = $this->input->post('iDisplayStart');
            $limit = $this->input->post('iDisplayLength');
            $data['employee'] = $this->admin_details_model->get_all_admin($limit, $start); //your model function from where you can get the data.
            $total_records = $filtered_records = $this->admin_details_model->total_admin_records(); //model functions to get total records
            $output = array(
                "sEcho"                => intval($this->input->post('sEcho')),
                "iTotalRecords"        => $total_records,
                "iTotalDisplayRecords" => $filtered_records,
                "aaData" => array()
            );
            foreach($data['employee'] as $post) 
                $action = '<a title="Edit" href="'.site_url("admin/edit/".md5($post->id)).'"><i class="fa fa-fw fa-edit"></i></a> <a title="Delete" class="delete-global" datatable-var="admin_table" href="'.site_url("admin/delete/".md5($post->id)).'"><i class="fa fa-fw fa-trash"></i></a>';
                $aaData   = array();
                $aaData[] = $post->first_name.' '.$post->last_name;
                //$aaData[] = $post->last_name;
                $aaData[] = $post->email;
                $aaData[] = $post->phone;
                $aaData[] = $post->status;
                $aaData[] = $action;
                $output['aaData'][] = $aaData;
            
            echo json_encode($output);
         else 
            redirect('login'); // redirect to your default page if any one try to access directly.
        
    

在你的 JS 中

$(document).ready(function () 

    if($('#admin_list').length > 0)
        var emp_table = $('#admin_list').dataTable(
            "aoColumns": [
               "bSortable": false ,
               "bSortable": false ,
               "bSortable": false ,
               "bSortable": false ,
               "bSortable": false ,
            ],
            'bProcessing'   : true,
            "bServerSide": true,
            "sAjaxSource": 'http://localhost/admin/admin/datatable', //put your ajax source url
            "sPaginationType": "full_numbers",
            "sDom": "t<'row'<'col-sm-6'i><'col-sm-6'p>>", // put your SDOM as this is little bit different as I have hide the header options of datatables
            "fnServerData": function (sSource, aoData, fnCallback)
            
                $.ajax
                        (
                            'dataType': 'json',
                            'type': 'POST',
                            'url': sSource,
                            'data': aoData,
                            'success': fnCallback
                        );
            ,
             "oLanguage": 
                "sLengthMenu": "_MENU_ records per page",
                "sZeroRecords": "No data available",
            ,
        );
    
);

在视图中

<div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><?php echo 'admin_list'; ?></h3>
            </div>
            <div class="panel-body">
                <div class="table-responsive dt-custom">
                    <table id="admin_list" class="table table-bordered table-hover table-striped">
                        <thead>
                            <tr>
                                <th><?php echo lang('full_name'); ?></th>
        <!--                        <th><?php //echo lang('last_name'); ?></th>-->
                                <th><?php echo 'email'; ?></th>
                                <th><?php echo 'phone'; ?></th>
                                <th><?php echo 'status'; ?></th>
                                <th><?php echo 'action'; ?></th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>
        </div>    
    </div>

请按照我在代码中提到的 cmets 进行操作,并根据您的要求设置数据表选项。希望这对你有用。

【讨论】:

好的,我试试看。【参考方案2】:

如果服务器没有使用有效的 JSON 数据回复 Ajax 请求,我们需要知道它回复了什么,以便我们采取纠正措施。通常,响应将包含来自服务器上用于创建 JSON 的程序的错误消息,这将是完全解决问题的起点。

//我用的是谷歌浏览器 1. Ctrl+Shift+I 打开开发者工具 2. 转到网络选项卡 3.查看ajax响应......(我可能是你的数据有错误...... 4.纠正任何错误

【讨论】:

以上是关于无效的 JSON 响应:引导数据表的主要内容,如果未能解决你的问题,请参考以下文章

jquery数据表中的无效json响应

无效的 JSON 响应 Jquery 数据表

数据表抛出无效的 JSON 响应

Laravel 数据表无效的 JSON 响应

jquery Datatable 无效 JSON 响应 1 ,数据被检查为有效 json

当我从数据库加载法语文本时,数据表返回无效的 json 响应