douhan8892 2016-01-16 19:51
浏览 50
已采纳

数据表库在CodeIgniter 3中不起作用

I'm trying the Datatables Library on CodeIgniter 3, but it doesn't work in CI3. I've tried this example in CodeIgniter 2 and it works perfectly but I want this library on CodeIgniter 3.

What do I need to change in order for it to work with CodeIgniter 3?

  • 写回答

1条回答 默认 最新

  • dqp10099 2016-01-19 07:39
    关注

    create Person_model.php in model directory

    <?php defined('BASEPATH') OR exit('No direct script access allowed');
         class Person_model extends CI_Model {
               var $table = 'persons';
               var $column = array('firstname','lastname','gender','address','dob');
              var $order = array('id' => 'desc');
    
        public function __construct()
        {
            parent::__construct();
            $this->load->database();
        }
    
         private function _get_datatables_query()
        {
            $this->db->from($this->table);
            $i = 0;
            foreach ($this->column as $item)
            {
                if($_POST['search']['value'])
                    ($i===0) ? $this->db->like($item, $_POST['search']['value']) : $this->db->or_like($item, $_POST['search']['value']);
                $column[$i] = $item;
                $i++;
            }
    
            if(isset($_POST['order']))
            {
                $this->db->order_by($column[$_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();
        }
    

    create controller file Person.php

        <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Person extends CI_Controller {
    
        public function __construct()
        {
            parent::__construct();
            $this->load->model('person_model','person');
        }
    
         public function index()
        {
            $this->load->helper('url');
            $this->load->view('person_view');
        }
    
        public function ajax_list()
        {
            $list = $this->person->get_datatables();
            $data = array();
            $no = $_POST['start'];
            foreach ($list as $person) {
                $no++;
                $row = array();
                $row[] = $person->firstName;
                $row[] = $person->lastName;
                $row[] = $person->gender;
                $row[] = $person->address;
                $row[] = $person->dob;
                $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);
        }
    

    and the last create for view. person_view.php at views directory

    <!DOCTYPE html>
    <html>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Ajax CRUD with Bootstrap modals and Datatables</title>
        <link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
        <link href="<?php echo base_url('assets/datatables/css/dataTables.bootstrap.css')?>" rel="stylesheet">
        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
      </head>
      <body>
    
      <div class="container">
        <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
          <thead>
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Gender</th>
              <th>Address</th>
              <th>Date of Birth</th>
              <th style="width:125px;">Action</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
    
          <tfoot>
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Gender</th>
              <th>Address</th>
              <th>Date of Birth</th>
              <th>Action</th>
            </tr>
          </tfoot>
        </table>
      </div>
    
      <script src="<?php echo base_url('assets/jquery/jquery-2.1.4.min.js')?>"></script>
      <script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>"></script>
      <script src="<?php echo base_url('assets/datatables/js/jquery.dataTables.min.js')?>"></script>
      <script src="<?php echo base_url('assets/datatables/js/dataTables.bootstrap.js')?>"></script>
    
      <script type="text/javascript">
    
        var save_method; //for save method string
        var table;
        $(document).ready(function() {
          table = $('#table').DataTable({
    
            "processing": true, //Feature control the processing indicator.
            "serverSide": true, //Feature control DataTables' server-side processing mode.
    
            // Load data for the table's content from an Ajax source
            "ajax": {
                "url": "<?php echo site_url('person/ajax_list')?>",
                "type": "POST"
            },
    
            //Set column definition initialisation properties.
            "columnDefs": [
            {
              "targets": [ -1 ], //last column
              "orderable": false, //set not orderable
            },
            ],
    
          });
        });
    
    
        function reload_table()
        {
          table.ajax.reload(null,false); //reload datatable ajax
        }
    
      </script>
      </body>
    </html>
    

    the SQL to create table :

    create database crud; use crud; CREATE TABLE persons ( id int(11) unsigned NOT NULL AUTO_INCREMENT, firstName varchar(100) DEFAULT NULL, lastName varchar(100) DEFAULT NULL, gender enum('male','female') DEFAULT NULL, address varchar(200) DEFAULT NULL, dob date DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样