【问题标题】:Send data in json and display in datatable以json形式发送数据并在datatable中显示
【发布时间】:2021-03-11 10:42:31
【问题描述】:

谁能帮助我如何在数据表中显示我的数据?我正在尝试服务器端数据表,但我无法得到它。无论如何,我可以以 JSON 格式返回我的数据,但我总是收到此错误:DataTables 警告:表 id=show-employee-table - 无法重新初始化 DataTable。

这些是我尝试过的:

ajax.js

var url = '../../class/functions.php';

function show_employee() {
    var data = { action : 'Show Employee Table' };
    $("#show-employee-table").dataTable({
        ajax: {
            type: 'POST', url: url, data: data
        }
    })
}

functions.php

<?php 
    include 'config.php';

    switch($_POST['action']) {
        case 'Show Employee Table':
            $data->show_employee_table();
        break;
    }

?>

class.php

<?php
    include 'controller.php';

    class db extends Controller {
        //Get all employees
        public function get_employee() {
            $query = $this->db->query("SELECT * FROM tbl_accounts WHERE employee_role_id = 2");
            return $query;
        }

        public function show_employee_table() {
            foreach($this->get_employee() as $row): ?>
                <?php $data = $row; ?>
                <?php $employee_status = ($row['employee_status'] == "Active") ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-danger">Not Active</span>';?>
                    
            <?php endforeach;
    
            echo json_encode(['data' => $data]);
        }
    }
?>

controller.php

<?php
    class Controller {
        public $host                = 'localhost';
        public $database_username   = 'root';
        public $database_password   = '';
        public $database_name       = 'try_db';
        public $db;
        
        function __construct() {
            $this->connection();
        }

        private function connection() {
            $this->db = new mysqli($this->host, $this->database_username, $this->database_password, $this->database_name);
            if($this->db->connect_error) {
                echo 'Could not connect to the database!';
            }
        }
    }
?>

config.php

<?php
    session_start();
    ob_start();
    include 'class.php';
    //include 'init.php';
    $data = new db();
?>

【问题讨论】:

  • 为什么class.php上有&lt;?php标签?如果您发布完整的 class.php 文件,我可能会为您提供帮助。
  • 我会编辑它。等一下。
  • 已编辑。你能检查一下吗?非常感谢! @ThamiraMadusanka

标签: php ajax datatables datatables-1.10


【解决方案1】:

我这样做的方法是通过 ajax 或页面加载将我的数据或记录提取到表中,然后在 ajax 成功或这样做之后调用 datatables。

$.ajax
   ({
       url:URL,
       type:"post",
       data:DATA,
       success:function(response)
       {
        //response should be the data of rows intended to be inserted into the table

         $("#show-employee-table").html(response)
           
         $("#show-employee-table").dataTable()
       }
   })

无需返回 JSON 数据

【讨论】:

    【解决方案2】:

    尝试像这样更新 ajax.js

     $("#show-employee-table").dataTable({
               "processing": true,
               "serverSide": true,
               "ajax": {
                   "url": url,
                   "type": "POST",
                   "data": data
           },
        })
    

    完整示例:

    index.php

        <!doctype html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport"
                  content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>DataTable Demo</title>
            <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
            <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
            <link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"/>
            <!-- Latest compiled and minified CSS -->
            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
        </head>
        <body>
        <div class="container mt-3">
            <table id="example" class="display" style="width:100%">
                <thead>
                <tr>
                    <th>First name</th>
                    <th>Middle name</th>
                    <th>Last name</th>
                </tr>
                </thead>
                <tfoot>
                <tr>
                    <th>First name</th>
                    <th>Middle name</th>
                    <th>Last name</th>
                </tr>
                </tfoot>
            </table>
        </div>
    
            <script>
                $(document).ready(function() {
    
               
                    $('#example').DataTable( {
                        "processing": true,
                        "serverSide": true,
                        "ajax": {
                            "url": "Functions.php",
                            "type": "POST",
                            "data": { action : 'Show Employee Table' }
                        },
                        "columns": [
                            { "data": "first_name" },
                            { "data": "middle_name" },
                            { "data": "last_name" }
                        ]
                    } );
                } );
            </script>
        </body>
    
    </html>
    

    DBConnect.php

    <?php
    
    class DBConnect
    {
        public $host                = 'localhost';
        public $database_username   = 'root';
        public $database_password   = '';
        public $database_name       = 'try_db';
        public $db;
    
        public function connect() {
            $this->db = new mysqli($this->host, $this->database_username, $this->database_password, $this->database_name);
            if($this->db->connect_error) {
                echo 'Could not connect to the database!';
            }
            return $this->db;
        }
    }
    

    控制器.php

    <?php
    include 'DBConnect.php';
    
    class Controller
    {
        private $db;
    
        public function __construct()
        {
            $connect = new DBConnect();
            $this->db = $connect->connect();
        }
    
        public function getEmployeeDetails()
        {
            $sql = "SELECT * FROM employees";
            $result = $this->db->query($sql);
            $response = [];
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $response[] = $row;
                }
            }
            // in this total records and page number should be dynamic for this example I just hardcoded it
            echo json_encode([ "draw" => 1, "recordsTotal" => 2, "recordsFiltered" => 2, 'data' => $response]);
        }
    }
    

    函数.php

    <?php
    include 'Controller.php';
    $controller = new Controller();
    $action = $_POST['action'];
    
    switch ($action) {
        case 'Show Employee Table':
            $controller->getEmployeeDetails();
            break;
        default:
            break;
    }
    

    【讨论】:

    • 不工作。我仍然收到此错误:DataTables 警告:table id=show-employee-table - 无法重新初始化 DataTable。
    • 我认为问题在于您构建代码的方式。很难理解。所以我创建了一个与您的非常相似的示例项目。所以我会编辑这个答案。希望对您有所帮助。 :)
    • 我会试试的。谢谢!
    【解决方案3】:

    错误

    错误:DataTables 警告:table id=show-employee-table - 无法重新初始化 DataTable。

    是一个很常见的。事实上,他们有一个专门的页面来说明这个错误的原因和诊断。

    见:https://datatables.net/manual/tech-notes/3

    简单地说 - 您只能初始化一次 DataTable,后续调用(带有选项)会导致错误。

    您有选择,请参阅文档。

    至于答案试试这个。

    controller.php

    <?php
    
    class Controller {
        public $host                = 'localhost';
        public $database_username   = 'root';
        public $database_password   = '';
        public $database_name       = 'try_db';
        public $db;
        
        function __construct() {
            $this->connection();
        }
    
        private function connection() {
            $this->db = new mysqli(
                $this->host, 
                $this->database_username, 
                $this->database_password, 
                $this->database_name
            );
    
            if($this->db->connect_error) {
                die 'Could not connect to the database!';
            }
        }
    }
    

    config.php

    <?php
    
    session_start();
    ob_start();
    require_once 'class.php';
    $data = new db();
    

    class.php

    <?php
    
    require_once 'controller.php';
    
    class db extends Controller {
    
        /** Get all employees */
        public function get_employee() {
            if (!($query = $this->db->query("SELECT * FROM tbl_accounts WHERE employee_role_id = 2"))) {
                die "Could not execute query"
            };
    
            return $query->fetch_all(MYSQLI_ASSOC);
        }
    
        public function show_employee_table() {
            echo json_encode(['data' => $this->get_employee()]);
        }
    }
    

    functions.php

    <?php 
        require_once 'config.php';
    
        switch($_POST['action']) {
            case 'Show Employee Table':
                $data->show_employee_table();
            break;
        }
    

    ajax.js

    var url = '../../class/functions.php';
    var dtTable = null;
    
    $(function() {
        dtTable = $("#show-employee-table").dataTable({
            ajax: {
                type: 'POST', 
                url: url, 
                data: {
                    action : 'Show Employee Table'
                }
            }
        });
    })
    
    function refreshDT() {
        dtTable.ajax.reload();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多