You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP PDO+Ajax实现Bootstrap DataTables数据填充失败求助

最简PHP PDO + Ajax 实现 Bootstrap DataTables 数据填充

1. HTML 页面(index.html)

先引入依赖资源,再写基础表格结构:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>DataTables 示例</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
</head>
<body>
    <div class="container mt-4">
        <table id="dataTable" class="table table-striped table-bordered" style="width:100%">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>邮箱</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

    <!-- 初始化DataTables -->
    <script>
        $(document).ready(function() {
            $('#dataTable').DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": "fetch.php",
                "columns": [
                    { "data": "id" },
                    { "data": "username" },
                    { "data": "email" }
                ]
            });
        });
    </script>
</body>
</html>

2. 数据库连接文件(db.php)

用PDO实现稳定连接,替换为你的数据库信息:

<?php
$host = 'localhost';
$dbname = '你的数据库名';
$username = '数据库用户名';
$password = '数据库密码';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}
?>

3. 数据接口文件(fetch.php)

严格按照DataTables要求的JSON格式返回数据,这是核心:

<?php
require 'db.php';

// 获取DataTables发送的分页参数
$draw = isset($_GET['draw']) ? intval($_GET['draw']) : 1;
$start = isset($_GET['start']) ? intval($_GET['start']) : 0;
$length = isset($_GET['length']) ? intval($_GET['length']) : 10;

// 查询总记录数
$totalStmt = $pdo->query("SELECT COUNT(*) FROM users");
$totalRecords = $totalStmt->fetchColumn();

// 查询分页数据(替换users为你的表名,字段对应自身表结构)
$stmt = $pdo->prepare("SELECT id, username, email FROM users LIMIT :start, :length");
$stmt->bindParam(':start', $start, PDO::PARAM_INT);
$stmt->bindParam(':length', $length, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 构造DataTables要求的响应结构
$output = [
    "draw" => $draw,
    "recordsTotal" => $totalRecords,
    "recordsFiltered" => $totalRecords, // 无搜索时与总记录数一致,有搜索需重新计算
    "data" => $data
];

// 输出JSON格式响应
header('Content-Type: application/json');
echo json_encode($output);
?>

关键排查点

  • 确认数据库表(示例为users)存在,且字段与代码中查询的字段匹配,可根据自身表结构修改查询语句和columns配置。
  • 直接在浏览器访问fetch.php,检查是否返回合法JSON,若有PHP报错会直接显示,可快速定位问题。
  • 打开浏览器控制台(F12),查看Network标签下的Ajax请求,检查请求状态(200为正常)和响应内容,确认是否有数据返回。
  • 如需添加搜索功能,在fetch.php中处理search[value]参数,修改查询语句加入WHERE条件,同时更新recordsFiltered为过滤后的记录数。

内容的提问来源于stack exchange,提问作者albert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:25:18