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;

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?