gpt4 book ai didi

javascript - DataTables 不会加载 AJAX 和 MYSQL

转载 作者:行者123 更新时间:2023-11-30 21:38:34 25 4
gpt4 key购买 nike

不知何故,我从这段代码中得到了一个无效的 JSON 响应。目标是在表中显示具有搜索和排序功能的 SQL 数据 https://datatables.net/ .问题出在哪里?

GET.PHP

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$query ="SELECT * FROM users";
$result = $mysqli->query($query);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results = ["sEcho" => 1,
"iTotalRecords" => count($row),
"iTotalDisplayRecords" => count($row),
"aaData" => $row ];
echo json_encode($results, JSON_PRETTY_PRINT);
}
} else {
echo "empty table";
}

$mysqli->close();

GET.PHP 响应

{
"sEcho": 1,
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"aaData": {
"id": "26",
"name": "test",
"pass": "2"
}
}

JS

$(document).ready(function() {
$('#my-example').dataTable({
"bProcessing": true,
"sAjaxSource": "get.php",
"aoColumns": [{
mData: 'name'
}, {
mData: 'pass'
}]
});
});

HTML

<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<table id="my-example">
<thead>
<tr>
<th>name</th>
<th>pass</th>
</tr>
</thead>
</table>

最佳答案

您的 PHP 代码返回的数组应该如下所示,它有义务将 data 作为您返回的数据,并将 error 作为最终错误:

{
"data": [
[
"Text going into the first column",
"second column",
"third column"
]
]
}

所以在你的情况下,你的数组看起来是这样的:

[
"data": [
[
"1",
count($data),
count($data),
$data
]
]
]

同样在循环中你需要得到 each row separately通过使用 $row['column']

Test case

关于javascript - DataTables 不会加载 AJAX 和 MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52776572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com