【问题标题】:How to get the data for a DataTable from the Controller to View using Ajax如何使用 Ajax 从 Controller 获取 DataTable 的数据到 View
【发布时间】:2021-07-08 05:44:18
【问题描述】:

在我的主控制器中,我有一个从数据库中获取数据、对其进行格式化并将其输出为 JSON 的函数。我现在的问题是如何将这些数据显示到 DataTable。我阅读的大多数示例都将数据保存在与控制器不同的文件中。我希望数据来自控制器中的函数。如何调用该函数?

查看(SampleView.php)

<table id="example" class="display" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>EmpID</th>
      <th>FirstName</th>
      <th>LastName</th>
    </tr>
  </thead>       
</table>
<script type="text/javascript">
  $( document ).ready(function() {  
    var table = $('#example').DataTable( {
                   "ajax": "main/getDataFunction", 
                   // "ajax": "getDataFunction", 
                   // "ajax": "<?php echo base_url()."main/getDataFunction"; ?>",
                   // "ajax": { url: 'main/getDataFunction', type: 'POST' },
                   "bPaginate":true,
                   "bProcessing": true,
                   "pageLength": 10,
                   "columns": [
                     { mData: 'EmpID' } ,
                     { mData: 'FirstName' },
                     { mData: 'LastName' }
                   ]
                 });        
  });
</script>

控制器(Main.php)

function getDataFunction() {
  $sampleData = $this->db->getSampleData();

  $data = array();

  foreach($sampleData as $key) {
    array_push($data, array("EmpID" => $key->empID, 
                            "FirstName" => $key->firstName, 
                            "LastName" => $key->lastName));
  }

  $results = array("sEcho" => 1, 
                   "iTotalRecords" => count($data),
                   "iTotalDisplayRecords" => count($data),
                   "aaData"=>$data);

  echo json_encode($results);
}

echo json_encode($results) 的输出

{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":[{"EmpID":"1","FirstName":"JOHN","LastName":"DOE"}]}

【问题讨论】:

    标签: ajax codeigniter datatable


    【解决方案1】:

    我不确定 DataTable,但您可以做的是您可以使用 eval() 先评估 json 数据,然后将您的 json 响应值获取到视图中。

    我知道的老办法是——

    $.ajax(函数() { type : 'get', // 或 'post', 数据:{键:值},
    数据类型:'json', 成功:函数(响应){ var html_data = response.eval(); // 这将序列化你的数据对象 $('选择器').val(html_data.name); // $('selector').val(html_data.sEcho);根据您的代码输出。 // 或者 $('选择器').html(html_data); } });

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-28
    • 2019-08-24
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    相关资源
    最近更新 更多