Codeigniter - 如何从 ajax 获取数据表数据?

Posted

技术标签:

【中文标题】Codeigniter - 如何从 ajax 获取数据表数据?【英文标题】:Codeigniter - How to fetch datatable data from ajax? 【发布时间】:2017-07-30 13:57:45 【问题描述】:

我正在开发一个基于 CodeIgniter 的应用程序。代码如下:

控制器

public function index()
    $data = array(
            'record' => $this->Parameter_model->get_parameter('tbl_parameter')
        );
    $this->site->view('parameter', $data);

型号

public function get_parameter($table)
    $query = $this->db->query("select * from $table order by 'parameter_ID' ASC");
    if($query->num_rows() > 0)
        foreach($query->result_array() as $row)
            $data[] = $row;
        

        $query->free_result();
    

    else
        $data = NULL;
    

    return $data;

查看

<table id="parameter" class="listdata table table-bordered table-striped table-hover">
  <thead>
    <tr>
      <th class="text-nowrap">Parameter</th>
      <th class="text-nowrap">Method</th>
      <th class="text-nowrap">Type</th>
      <th class="text-nowrap">Action</th>
    </tr>
  </thead>
  <tbody>
    <?php if(!empty($record)):?>
      <?php foreach($record as $row):?>
        <tr align="center">
          <td class="text-nowrap"><a href="<?=set_url('parameter/parameter_view/'.$row['parameter_ID']);?>"><strong><?php echo $row['parameter_name'];?></strong></a></td>
          <td class="text-nowrap"><?php echo $row['parameter_method'];?></td>
          <td class="text-nowrap">
            <?php 
              if($row['parameter_type'] == "1")
                echo "General";
              
              else
                echo "COA Only";
              
            ?>
          </td>
          <td class="text-nowrap">
            <div>
              <a href="<?=set_url('parameter#edit?parameter_ID='.$row['parameter_ID']);?>" class="btn btn-warning btn-xs">Edit</a>
              <a href="<?=set_url('parameter/parameter_view/'.$row['parameter_ID']);?>" class="btn btn-success btn-xs">Lihat</a>
              <a href="<?=set_url('parameter#hapus?parameter_ID='.$row['parameter_ID']);?>" class="btn btn-danger btn-xs">Hapus</a>
            </div>
          </td>
        </tr>
      <?php endforeach;?>
    <?php endif;?>
  </tbody>
  <tfoot>
    <tr>
      <th class="text-nowrap">Parameter</th>
      <th class="text-nowrap">Method</th>
      <th class="text-nowrap">Type</th>
      <th class="text-nowrap">Action</th>
    </tr>
  </tfoot>
</table>

Javascript

// parameter
// Setup - add a text input to each footer cell
$('#parameter tfoot th').each( function () 
    var title = $(this).text();
    $(this).html( '<input type="text" style="width:100%;" title="Search '+title+'" placeholder="Search '+title+'" />' );
 );

// DataTable
var table = $('#parameter').DataTable(
    paging: true,
    searching: true,
    ordering: true,
    "order": [[ 0, "asc" ]],
    scrollX: true,
    scroller: true,
);

// Apply the search
table.columns().every( function () 
    var that = this;

    $( 'input', this.footer() ).on( 'keyup change', function () 
        if ( that.search() !== this.value ) 
            that
                .search( this.value )
                .draw();
        
     );
 );

以上代码运行良好。

现在,我想通过 ajax 请求将数据提取到 table id="parameter" 中。我已经从 url 创建了一个 ajax 请求,让我们说从这里http://'+host+path+'/action/ambil,其中var path = window.location.pathname;var host = window.location.hostname;

ajax 响应产生:

"record":["parameter_ID":"1","parameter_name":"pH","parameter_method":"(pH meter)","parameter_type":"1","parameter_ID":"2","parameter_name":"Viscosity","parameter_method":"(***field-Viscometer)","parameter_type":"1"]

问题 如何使用Ajax数据源配置datatable,以及如何将数据显示到表中,以便我可以使用数据创建链接,如代码&lt;a href="&lt;?=set_url('parameter/parameter_view/'.$row['parameter_ID']);?&gt;"&gt;

【问题讨论】:

【参考方案1】:

你可以通过server side脚本来做dataTable如下。

    更改您的控制器,使其能够处理来自数据表的服务器端调用,并且您只能在控制器中创建动态链接。我已在控制器中添加评论以获取更多详细信息。 更改您的脚本以使用 ajax 调用它。 在加载页面时不要在视图 tbody 中加载任何东西。 注意:我已经跳过了我使用直接查询的模型部分。希望你能改变它。

控制器

public function index() 
        $data = array();
        if ($this->input->is_ajax_request()) 
            /** this will handle datatable js ajax call * */
            /** get all datatable parameters * */
            $search = $this->input->get('search');/** search value for datatable  * */
            $offset = $this->input->get('start');/** offset value * */
            $limit = $this->input->get('length');/** limits for datatable (show entries) * */
            $order = $this->input->get('order');/** order by (column sorted ) * */
            $column = array('parameter', 'method', 'type');/**  set your data base column name here for sorting* */
            $orderColumn = isset($order[0]['column']) ? $column[$order[0]['column']] : 'parameter';
            $orderDirection = isset($order[0]['dir']) ? $order[0]['dir'] : 'asc';
            $ordrBy = $orderColumn . " " . $orderDirection;

            if (isset($search['value']) && !empty($search['value'])) 
                /** creat sql or call Model * */
                /**   $this->load->model('Parameter_model');
                  $this->Parameter_model->get_parameter('tbl_parameter'); * */
                /** I am calling sql directly in controller for your answer 
                 * Please change your sql according to your table name
                 * */
                $sql = "SELECT * FROM TABLE_NAME WHERE column_name '%like%'" . $search['value'] . " order by " . $ordrBy . " limit $offset,$limit";
                $sql = "SELECT count(*) FROM TABLE_NAME WHERE column_name '%like%'" . $search['value'] . " order by " . $ordrBy;
                $result = $this->db->query($sql);
                $result2 = $this->db->query($sql2);
                $count = $result2->num_rows();
             else 
                /**
                 * If no seach value avaible in datatable
                 */
                $sql = "SELECT * FROM TABLE_NAME  order by " . $ordrBy . " limit $offset,$limit";
                $sql2 = "SELECT * FROM TABLE_NAME  order by " . $ordrBy;
                $result = $this->db->query($sql);
                $result2 = $this->db->query($sql2);
                $count = $result2->num_rows();
            
            /** create data to display in dataTable as you want **/    

            $data = array();
            if (!empty($result->result())) 
                foreach ($result->result() as $k => $v) 
                    $data[] = array(
                        /** you can add what ever anchor link or dynamic data here **/
                         'parameter' =>  "<a href=".set_url('parameter/parameter_view/'.$v['parameter_ID'])."><strong>".$v['parameter_name']."</strong></a>",
                          'method' =>  "<a href=".set_url('parameter/parameter_view/'.$v['parameter_ID'])."><strong>".$v['parameter_name']."</strong></a>",
                          'parameter_type' =>  "<a href=".set_url('parameter/parameter_view/'.$v['parameter_ID'])."><strong>".$v['parameter_name']."</strong></a>",
                          'actions' =>  "<a href=".set_url('parameter/parameter_view/'.$v['parameter_ID'])."><strong>".$v['parameter_name']."</strong></a>" 

                    );
                
            
            /**
             * draw,recordTotal,recordsFiltered is required for pagination and info.
             */
            $results = array(
                "draw" => $this->input->get('draw'),
                "recordsTotal" => count($data),
                "recordsFiltered" => $count,
                "data" => $data 
            );

            echo json_encode($results);
         else 
            /** this will load by default with no data for datatable
             *  we will load data in table through datatable ajax call
             */
            $this->site->view('parameter', $data);
        
    

查看

   <table id="parameter" class="listdata table table-bordered table-striped table-hover">
  <thead>
    <tr>
      <th class="text-nowrap">Parameter</th>
      <th class="text-nowrap">Method</th>
      <th class="text-nowrap">Type</th>
      <th class="text-nowrap">Action</th>
    </tr>
  </thead>
  <tbody>
    /** tbody will be empty by default. **/
  </tbody>
  <tfoot>
    <tr>
      <th class="text-nowrap">Parameter</th>
      <th class="text-nowrap">Method</th>
      <th class="text-nowrap">Type</th>
      <th class="text-nowrap">Action</th>
    </tr>
  </tfoot>
</table>

脚本

 <script>
        $(document).ready(function() 
            $('#example').DataTable(
                url: '<?php base_url(); ?>controllerName/index',
                processing: true,
                serverSide: true,
                paging: true,
                searching: true,
                ordering: true,
                order: [[0, "asc"]],
                scrollX: true,
                scroller: true,
                columns: [data: "parameter", data: "method", data: "parameter_type", data: "action"]
                /** this will create datatable with above column data **/
            );
        );
    </script>

如果你想使用一些第三方库check this。 对于您的模型查询,您可以按照this post 中的说明对其进行自定义。

【讨论】:

抱歉回复晚了,我会根据您的回答尝试实施。【参考方案2】:

您可以查看此article。虽然我是使用原始 php 编写的,但您可以通过使用该 ssp 类创建一个单独的库来轻松实现它,并且可以创建这种类型的链接。

【讨论】:

有没有其他方法我们不需要创建单独的文件?【参考方案3】:

更新了更多解释和更多代码

你可以试试我的代码,这对我来说很好。

控制器代码

public function showFeeCode()

    $data = $this->fmodel->fetchAllData('*','fee_assign',array());
    if (is_array($data) || is_object($data))
    
        foreach ($data as $key => $value) 
            $button = "";
            $button .= "<button class='btn btn-success fa fa-pencil' onclick='editFunction(".$value['id'].")' data-toggle='tooltip' title='Edit Details'></button> ";
            $result['data'][$key] = array(
                    $value['feegroup'],
                    $value['name'],
                    $button
                     );
        
    
    echo json_encode($result);

模式代码

public function fetchAllData($data,$tablename,$where)
    
        $query = $this -> db 
                        ->where($where)
                        -> get($tablename);
                            
    if($query->num_rows() > 0)
            return $query->result_array();
        
        else
            return array('error');
        
    

查看代码(表格)

<table id="myTable" class="table display">
                      <thead class="alert alert-danger">
                          <tr>
                              <th>Fee Type</th>
                              <th>Fee Code</th>
                              <th>Action</th>
                          </tr>
                      </thead>
                  </table>

ajax 代码来获取 ajax 代码在视图页面中返回的数据。

$(document).ready(function() 
  $('#myTable').dataTable( 
        "ajax":"<?= base_url('Fee/showFeeCode'); ?>",
        'order':[],
    );
  );

如果你想将一些参数传递给控制器​​,那么你可以通过 ajax 传递它

 $(document).ready(function() 
var id = 4;
  $('#myTable').dataTable( 
        "ajax":"<?= base_url('Fee/showFeeCode'); ?>/"+id,
        'order':[],
    );
  );

您可以通过将参数传递给控制器​​函数来接收此 id。

如果你想发送多个数据,那么你可以使用这种格式

var first_data = 1;
var second_data = 2;
$('#myTable').dataTable( 
            "ajax": 
            "url": '<?php echo base_url('fetchData') ?>',
            "type": "POST",
            "data": first_data:first_data,second_data:second_data
             ,
            'order':[],
        );
      );

【讨论】:

【参考方案4】:

型号代码

  public function get_cities()

  $this->db->order_by('city_id','desc');
  $this->db->limit('1000');
  $this->db->select('*,cities.name as city_name');
  $this->db->from('cities');
  $this->db->join('states','states.id=cities.state_id','left');
  $this->db->join('countries','countries.id=states.country_id','left');
  $data=$this->db->get();
  return $data->result_array();
  
   private function get_datatables_query_city()
    $column_search = array('cities.name','states.name','countries.country_name');
    $order = array('city_id' => 'desc');
    $column_order = array(null, 'city_name', 'sname', 'country_name', null);
    $this->db->select('cities.city_id,cities.name as city_name,states.name as sname,states.id as state_id,countries.id as country_id,countries.country_name');
     $this->db->from('cities');
     $this->db->join('states','states.id=cities.state_id','left');
     $this->db->join('countries','countries.id=states.country_id','left');
     $i = 0;
     foreach ($column_search as $item)
     
        if($_POST['search']['value']) // if datatable send POST for search
            
                if($i===0)
                
                    $this->db->group_start();
                    $this->db->like($item, $_POST['search']['value']);
                
                else
                
                    $this->db->or_like($item, $_POST['search']['value']);
                
                if(count($column_search) - 1 == $i)
                $this->db->group_end();
        
        $i++;
    
    if(isset($_POST['order']))
    
        $this->db->order_by($column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
    
    else if(isset($order))
    
        $order = $order;
        $this->db->order_by(key($order), $order[key($order)]);
    

function get_datatables_city()

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

function count_filtered_city()

    $this->get_datatables_query_city();
    $query = $this->db->get();
    return $query->num_rows();

public function count_all_city()

    $this->db->from('cities');
    return $this->db->count_all_results();
 

控制器代码

 public function city_list()
        $this->load->view('admin/header');
        $this->load->view('admin/city');
        $this->load->view('admin/footer');
    
    public function city_ajax()
        $list = $this->Admin_model->get_datatables_city();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $city)
            $no++;
            $row = array();
            $row[] = $no;
            $row[] = $city->city_name;
            $row[] = $city->sname;
            $row[] = $city->country_name;
            $row[] = '<div class="d-flex align-items-center card-action-wrap">
            <div class="inline-block dropdown">
            <a class="dropdown-toggle no-caret" data-toggle="dropdown" href="#" aria-expanded="false" role="button"><i class="ion ion-ios-more"></i></a>
            <div class="dropdown-menu dropdown-menu-right" x-placement="top-end" style="position: absolute; transform: translate3d(-214px, -161px, 0px); top: 0px; left: 0px; will-change: transform;">
            <a class="dropdown-item" href="'.base_url().'Adminhome/city_edit/'.$city->city_id.'" ><i class="fas fa-edit read-icon"></i> Edit</a>
            <a id="mybutton" href="javascript:void(0);" onclick="citydelete('.$city->city_id.')" class="dropdown-item text-danger remove"  data-toggle="modal" data-target="#delete" data-id="'.$city->city_id.'"><i class="fas fa-trash-alt read-icon text-danger"></i> Delete</a>
            </div>
            </div>
            </div>';
            $data[] = $row;
        
        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->Admin_model->count_all_city(),
            "recordsFiltered" => $this->Admin_model->count_filtered_city(),
            "data" => $data,
        );
        echo json_encode($output);
    

查看代码

            <div class="section-body">
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="example">
                                        <thead>
                                            <tr>
                                                <th>Sr.Number</th>
                                                <th>City Name</th>
                                                <th>State Name</th>
                                                <th>Country</th>
                                                <th>Manage</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
    <div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    Are you sure want to delete.
                </div>
                <div class="modal-footer bg-whitesmoke br">
                    <a id="confirm-button"> <button type="button" class="btn btn-danger">Delete</button></a>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>
    <div class="alert alert-primary show2" role="alert" id="snackbar2" style="visibility: hidden">
        Successfully Deleted
    </div>
    <script>
        function citydelete(id)
            $('#delete').modal('show');
            rowToDelete = $(this).closest('tr');
            $('#confirm-button').click(function()
                 $.ajax(
                    url: '<?php echo base_url();?>/Adminhome/city_delete',
                    type: 'GET',
                    data: id: id,
                    success: function (data)
                        $("#"+id).remove();
                        var table = $('#example').DataTable();
                        table.ajax.reload( null, false );
                        $("#delete").modal('hide');
                        document.getElementById("snackbar2").style.visibility = "visible";
                        setTimeout(function() 
                            document.getElementById('snackbar2').style.visibility = 'hidden';
                        , 3000);
                    
                );
                )
        
    </script>
    <script type="text/javascript">
        var table;
        $(document).ready(function() 
            table = $('#example').DataTable( 
                "processing": true,
                "serverSide": true,
                "stateSave": true,
                "order": [],
                "ajax": 
                    "url": "<?php echo site_url('Adminhome/city_ajax')?>",
                    "type": "POST"
                ,
                "columnDefs": [
                 
                    "targets": [ 0 ],
                    "orderable": false,
                ,
                ],
            );
        );
    </script>   

【讨论】:

以上是关于Codeigniter - 如何从 ajax 获取数据表数据?的主要内容,如果未能解决你的问题,请参考以下文章

在 CodeIgniter 中使用 AJAX 从数据库中获取单行?

codeigniter 从控制器返回获取数据以通过 Ajax 请求查看

我无法将我的数组从我的控制器获取到 codeigniter 中的 ajax

如何在codeigniter中将ajax选择的依赖下拉选项传递给mysql数据库

Codeigniter AJAX 从 MySQL 数据库获取数据而不刷新的正确方法

如何选择具有多个选择值的数据作为 where 子句? - Ajax Codeigniter