我不太精通 JS/HTML。我需要从 Firebase 获取 JSON 格式的表,并使用 DataTables 很好地显示它。 我有一个工作代码,在 JSON.stringify 之后从 Firebase 获取数据:
[{
"Rings": 0,
"P_Bars": 0,
"First_Name": "Jane",
"Last_Name": "Dow",
"Vault": 10,
"Number": 101,
"H_Bar": 0,
"Level": "4_A",
"Pommel": 11.402,
"Floor": 0
}, {
"Pommel": 12.5,
"Vault": 7,
"Floor": 11.5,
"Level": "6_Optional",
"P_Bars": 10,
"H_Bar": 0,
"Number": 102,
"First_Name": "Steve",
"Last_Name": "Dark",
"Rings": 12
}]
我遇到以下错误:
DataTables 警告:表 id=test - 无效的 JSON 响应。有关此错误的更多信息,请参阅 http://datatables.net/tn/1
我的JS代码:
async function GetAllDataRealtime() {
const dbRef = collection(db, "Gymnasts");
onSnapshot(dbRef, (querySnapshot) => {
var gymnasts = [];
querySnapshot.forEach((doc) => {
gymnasts.push(doc.data());
});
return JSON.stringify(gymnasts);
});
}
var testdata = GetAllDataRealtime();
$(document).ready(function () {
$("#test").DataTable({
ajax: {
"data": testdata,
"dataType": "json",
},
columns: [
{ data: "Number" },
{ data: "First_Name" },
{ data: "Last_Name" },
{ data: "Rings" },
{ data: "Floor" },
{ data: "Pommel" },
{ data: "H_Bar" },
{ data: "P_Bars" },
{ data: "Vault" },
],
});
});
还有 HTML *(不过我认为问题不在这里)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test</title>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<link
rel="stylesheet"
href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.css"
/>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.js"></script>
<script type="module" src="script.js"></script>
<!-- <script src="db.js"></script> -->
</head>
<body>
<table id="test" class="display" style="width: 100%">
<thead>
<tr>
<th>Number</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rings</th>
<th>Floor</th>
<th>Pommel</th>
<th>H_Bar</th>
<th>P_Bars</th>
<th>Vault</th>
</tr>
</thead>
</table>
</body>
</html>
我尝试使用专用的 .json 文件并且它有效。 基于 https://datatables.net/manual/tech-notes/1 *(来自错误消息)我调查了 XHR/Request-Response,尽管安慰了“testdata”,但我什至无法在日志中看到正确的响应“显示正确的数组。使用 JSON 验证器进行测试 - 一切都很好。感觉我在这里错过了一些东西。
数据是从 Firestore(以及大多数云 API)异步加载的,但您的代码无法处理该问题。
您的代码中有两个异步事件:
您的代码需要处理这种异步性质,例如:仅在文档准备好以及从 Firestore 加载数据时创建数据表。
在可以这样完成的代码中:
$(document).ready(function () {
const dbRef = collection(db, "Gymnasts");
onSnapshot(dbRef, (querySnapshot) => {
var gymnasts = [];
querySnapshot.forEach((doc) => {
gymnasts.push(doc.data());
});
$("#test").DataTable({
ajax: {
"data": gymnasts,
"dataType": "json",
},
columns: [
{ data: "Number" },
{ data: "First_Name" },
{ data: "Last_Name" },
{ data: "Rings" },
{ data: "Floor" },
{ data: "Pommel" },
{ data: "H_Bar" },
{ data: "P_Bars" },
{ data: "Vault" },
],
});
});
});
所以这里我们只有在读取文档后才开始加载数据,然后在数据可用后设置数据表。由于您使用的是
onSnapshot
实时监听器,因此当基础数据更新时,数据表也会更新。
我强烈建议您在继续之前阅读并学习一些有关异步行为的教程,因为这是一个非常常见的混乱来源 - 并且您可能会多次陷入困境,直到您掌握异步代码。