【问题标题】:DataTables - Server-side dumping JSON data when echo json_encodeDataTables - echo json_encode 时服务器端转储 JSON 数据
【发布时间】:2018-02-15 03:15:44
【问题描述】:

我正在尝试使用 Codeigniter 应用服务器端数据表,我的控制器代码是:

 function get_logins() {

    $get_logins = $this->login_attempts_model->get_datatble();
    $data = array();
    foreach ($get_logins as $row){
        $subarray= array();
        $subarray[] = $row->id;
        $subarray[] = $row->ip_address;
        $subarray[] = $row->login_username;
        $subarray[] = $row->time;
        $subarray[] = $row->status;
        $subarray[] = '<button type="button" name="delete" id="'.$row->id.'"class="btn btn-danger">delete</button>';
        $data[]=$subarray;
    }
    $output = array(
        "draw" => $this->input->post(['draw']),
        "recordsTotal" => $this->login_attempts_model->get_all_data(),
        "recordsFiltered" => $this->login_attempts_model->count_filtered_data(),
        "data" => $data
    );
    echo json_encode($output);
}

我的视图代码包括 Jquery 是:

<script type="text/javascript">

    $('#login_data').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "ajax": {
            url: "<?= site_url('login_attempts/get_logins'); ?>",
            type: "POST",
            },
        "columnDefs": [
            {
                "targets": [4],
                "orderable": false,
            },
        ],
    });// also there are rest of other functions 
    </script>
<table id="login_data" class="table table-hover table-striped table-bordered results">
    <thead>
    <th>id</th>
    <th>IP Address</th>
    <th>Username </th>
    <th>Login Time</th>
    <th>actiona</th>
<th>Login Status</th>
</thead>
<tbody>
</tbody>
</table>

一切顺利,数据填满了表格,但echo json_encode($output) 正在将数据与 JSON 格式的数据转储到同一页面上,而不仅仅是由 AJAX 方法捕获。

【问题讨论】:

  • 如果您的 php 代码和 html 代码在同一个文件中,那么它将显示两个输出,一个在浏览器本身中,另一个在您使用 ajax 呈现。请将 php 代码放在一个单独的文件中并调用该外部文件。
  • 它不起作用,我试图这样做..仍然是同样的问题..
  • 试试这个方案发送json数据stackoverflow.com/a/28762310/4816207
  • 再次抱歉!!它不起作用,它将我重定向到 HTML 视图 @PrashantPokhriyal

标签: jquery json ajax datatables codeigniter-3


【解决方案1】:

处理这个问题的解决方案非常简单: 不要从 php 控制器调用方法 get_logins() 加载文档时添加ajax方法:

$(document).load(function () {
    $.ajax({
            url: 'login_attempts/get_logins',
            type: 'POST',
            dataType: 'json'
        });
});
这将解决从控制器调用方法并再次从 ajax 上的 .dataTbles() 方法内部调用的问题(看起来模棱两可,但这是我弄清楚的唯一解释)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    相关资源
    最近更新 更多