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

新手上路,请多包涵

我正在开发一个基于 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>

脚本

 // 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":"(Brookfield-Viscometer)","parameter_type":"1"}]}

问题

如何使用 Ajax 数据源配置数据表,以及如何将数据显示到表中,因此我可以使用数据来创建类似代码的链接

<a href="<?=set_url('parameter/parameter_view/'.$row['parameter_ID']);?>">

原文由 Firman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 284
2 个回答

您可以通过 服务器端 脚本执行数据表,如下所示。

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

控制器

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>

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

原文由 shafiq.rst 发布,翻译遵循 CC BY-SA 3.0 许可协议

型号代码

  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>

原文由 alok bhade 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题