无效的JSON响应:Bootstrap数据表

时间:2016-06-29 05:45:04

标签: jquery json codeigniter datatable datatables

我这里有一个数据表使用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>

2 个答案:

答案 0 :(得分:0)

尝试以下代码

在控制器中

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>

请根据您的要求,按照我提到的评论以及代码和设置数据表选项。希望这对你有用。

答案 1 :(得分:0)

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

//我正在使用谷歌浏览器 1.按Ctrl + Shift + I打开开发人员工具 2.转到网络选项卡 3.查看ajax响应...(Mybe这是您数据中的错误... 4.纠正任何错误