数据表服务器端实现

时间:2018-08-19 22:57:12

标签: php codeigniter datatable

我试图在服务器端实现数据表,因为我有一个很大的表,并且不能像通常的数据表那样返回它,但是我有一个问题,因为它不起作用,我无法理解正在发生的事情:

查看:

<table id="deposits" class="table table-bordered table-striped">
 <thead>
  <tr>
   <th>Id</th>
   <th>Sucursal</th>
  </tr>
 </thead>
</table>

JS:

$("#deposits").DataTable({
  "paging": true,
  "lengthChange": true,
  "searching": true,
  "ordering": true,
  "info": true,
  "autoWidth": true,
  'responsive': true,
  "processing": true,
  "serverSide": true,
  "ajax":{
            url :"<?php echo base_url(); ?>deposit/data", // json datasource
            type: "post",  // method  , by default get
            error: function(data) {  // error handling
               console.log(data);
            }
  },
  "columns": [
    { "data": "id" },
    { "data": "branch_name" },
    ],
  "columnDefs": [
        {
            "targets": [ 1 ],
            "visible": false,
            "searchable": false
        },
        {
            "targets": [ 2 ],
            "visible": false
        }
   ],
  "language": {
        "sProcessing":     "Procesando...",
        "sLengthMenu":     "Mostrar _MENU_ registros",
        "sZeroRecords":    "No se encontraron resultados",
        "sEmptyTable":     "Ningún dato disponible en esta tabla",
        "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
        "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
        "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
        "sInfoPostFix":    "",
        "sSearch":         "Buscar: ",
        "sUrl":            "",
        "sInfoThousands":  ",",
        "sLoadingRecords": "Cargando...",
         "oPaginate": {
            "sFirst":    "Primero",
            "sLast":     "Último",
            "sNext":     "Siguiente",
            "sPrevious": "Anterior"
        },
        "oAria": {
            "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
            "sSortDescending": ": Activar para ordenar la columna de manera descendente"
        },
    },
    "order": [[ 8, "desc" ]],
});

控制器:

public function data()
{
    $data = array(
                'id_user' => $this->session->userdata('id_user'),
                'activity_type' => 4,
                );

    $this->activity_model->store($data);

    $id_status = $this->uri->segment(2);

    if($this->session->userdata('id_user_type') == 4)
    {
        $data = array(

        'id_supervisor' => $this->session->userdata('id_user'),
        'id_status' => $id_status,
        'start' => $this->input->post('start'),
        'length' => $this->input->post('length'),

        );

        $result = $this->deposit_model->getDataTableDeposits($data);
    }
    else
    {
        if($id_status != "")
        {
            $data = array(

            'id_status' => $id_status,
            'start' => $this->input->post('start'),
            'length' => $this->input->post('length'),

            );
        }
        else
        {
            $data = array(

            'start' => $this->input->post('start'),
            'length' => $this->input->post('length'),

            );
        }

        $result = $this->deposit_model->getDataTableDeposits($data);
    }

    $data = $result['data'];
    $recordsTotal = $result['numDataTotal'];

    for ($i = 0; $i < $recordsTotal; $i++) {
        $array = array();
        $array['id_deposit'] = $data[$i]['id_deposit'];
        $array['branch_office'] = $data[$i]['branch_office'];
        $new_data[] = $array;
    }

    $recordsFiltered = $recordsTotal;

    $json_data = array(
        "draw"            => intval($this->input->post('draw')),
        "recordsTotal"    => intval($recordsTotal),
        "recordsFiltered" => intval($recordsFiltered),
        "data"            => $new_data
        );

    echo json_encode($json_data);
}

型号:

function getDataTableDeposits($data = NULL)
{
    $this->db->select('deposits.*, branch_offices.*, statuses.*, DATE_FORMAT(deposits.date,"%d/%m/%Y") AS date,  DATE_FORMAT(deposits.collection_date,"%d/%m/%Y") AS collection_date');
    $this->db->from('deposits, branch_offices, statuses');
    $this->db->where("deposits.id_branch_office = branch_offices.id_branch_office");
    $this->db->where("deposits.id_status = statuses.id_status");
    $this->db->limit($data['start'], $data['length']);

    if(isset($data['id_status']))
    {
        $this->db->where("deposits.id_status != 7");
    }
    else
    {
        $this->db->where("deposits.id_status = 7");
    }

    $this->db->order_by("deposits.date", "desc");

    if(isset($data['id_supervisor'])) 
    {
        $this->db->where("deposits.id_supervisor = '".$data['id_supervisor']."'");
    }  

    $query = $this->db->get();

    $return = array(
        'numDataTotal' => $query->num_rows(),
        'data' => $query->result_array()
        );

    return $return;
}

但是问题是它没有返回任何东西,只是保持为空,只显示标题ID和Sucursal,但没有数据。

那会是什么?因为我已经学习了一些课程,但我不太了解我还需要什么...

谢谢。

1 个答案:

答案 0 :(得分:0)

这将为您提供帮助。几天前,我还使用服务器端实现了数据表,我将排序部分最小化以节省资源,并使查询变得更快,更简单

HTML和JS PART

    <table class="table table-hover table-bordered table-bordered" id='neodatatable' style="border:none;">
    <thead>
      <tr>
        <th class="tableheaddata">Trainee ID</th>
        <th class="tableheaddata">Trainee Name</th>
        <th class="tableheaddata">Father Name</th>
        <th class="tableheaddata">DOB</th>
        <th class="tableheaddata">Address</th>
        <th class="tableheaddata">Document No</th>
        <th class="tableheaddata">DPR</th>
        <th class="tableheaddata">Center</th>
        <th class="tableheaddata">Sub Center</th>
        <th class="tableheaddata">Course</th>
      </tr>
    </thead><tfoot>
      <tr>
        <th class="tableheaddata">Trainee ID</th>
        <th class="tableheaddata">Trainee Name</th>
        <th class="tableheaddata">Father Name</th>
        <th class="tableheaddata">DOB</th>
        <th class="tableheaddata">Address</th>
        <th class="tableheaddata">Document No</th>
        <th class="tableheaddata">DPR</th>
        <th class="tableheaddata">Center</th>
        <th class="tableheaddata">Sub Center</th>
        <th class="tableheaddata">Course</th>
      </tr>
    </tfoot>
  </table>



    <script type="text/javascript">
    $(document).ready(function () {


        $('#neodatatable').DataTable({
            "ordering": false,
            "processing": true,
            "serverSide": true,
            "ajax": {
                url: '<?=base_url();?>others/data_view/traineeview',
                type: 'POST'

            },
            columnDefs: [
                { targets: [0, 1], orderable: false},
            ]
        });
    });
</script>

服务器端我正在控制器中做所有事情

     parent::__construct();

      /* Useful $_POST Variables coming from the plugin */
        $this->draw = $this->input->post('draw');//$_POST["draw"];//counter used by DataTables to ensure that the Ajax returns from server-side processing requests are drawn in sequence by DataTables
     // $orderByColumnIndex  =  $this->input->post('order')[0]['column'];// index of the sorting column (0 index based - i.e. 0 is the first record)
     //$orderBy =  $this->input->post('columns')[$orderByColumnIndex]['data'];//Get name of the sorting column from its index
    // $orderType =  $this->input->post('order')[0]['dir']; // ASC or DESC
        $this->start  = $this->input->post('start');//$_POST["start"];//Paging first record indicator.
        $this->length = $this->input->post('length');//$_POST['length'];//Number of records that the table can display in the current draw
        $this->search = $this->input->post('search');


}

function traineeview(){

    $recordsTotal=$this->db->order_by('id','DESC')->count_all_results('fddi_trainee_registration');




    $this->db->limit($this->length,$this->start);

    if(!empty($this->search['value'])){

        $this->db->group_start();
        $this->db->or_like('aadhar',$this->search['value']);
        $this->db->or_like('t_first_name',$this->search['value']);
        $this->db->or_like('t_last_name',$this->search['value']);
        $this->db->or_like('t_middle_name',$this->search['value']);
        $this->db->or_like('fddi_trainee_registration.id',$this->search['value']);
        $this->db->group_end();


        $getlists=$this->db->order_by('id','DESC')->get_where('fddi_trainee_registration',array());
        $recordsFiltered = $getlists->num_rows();

    }else{


        $getlists=$this->db->order_by('id','DESC')->get_where('fddi_trainee_registration',array());

        $recordsFiltered = $recordsTotal;
    }



        $data=array();

            foreach($getlists->result() as $rowdata){


            $data[]= array(
            $rowdata->id,$rowdata->t_first_name.' '.$rowdata->t_middle_name.' '.$rowdata->t_last_name,$rowdata->f_first_name.' '.$rowdata->f_middle_name.' '.$rowdata->f_last_name,formateDate($rowdata->dob),$rowdata->address,$rowdata->aadhar,$dpr,$center,$subcenter,$course);


        }

         $response = array(
                "draw" => intval($this->draw),
                "recordsTotal" => $recordsTotal,
                "recordsFiltered" => $recordsFiltered,
                "data" => $data
                );

        echo json_encode($response);

}

任何清晰的评论