簡體   English   中英

Codeigniter-如何從Ajax獲取數據表數據?

[英]Codeigniter - How to fetch datatable data from 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>

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


如何使用Ajax數據源配置數據表,以及如何將數據顯示到表中,因此我可以使用數據例如創建類似代碼的鏈接
<a href="<?=set_url('parameter/parameter_view/'.$row['parameter_ID']);?>">

您可以按以下方式通過服務器端腳本執行dataTable。

  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>

如果您想使用某些第三方庫, 請選中此選項 為了您的型號查詢,你可以自定義在提這個職位

您可以查看這篇文章 盡管我使用原始php編寫了它,但是您可以通過使用該ssp類創建一個單獨的庫來輕松實現它,並且可以創建這種類型的鏈接。

更新了更多解釋和更多代碼

您可以嘗試我的代碼,這對我來說很好。

控制器代碼

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':[],
        });
      });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM