如何将Firestore文档中的所有数据显示到html表中 [英] How can I display all data from Firestore documents into an html table
问题描述
我正在设计一个将从Firestore集合中获取数据并显示每个文档及其相应字段的网页,这是代码:
I am designing a web page that will obtain data from my firestore collection and display each document with its corresponding fields Here is the code:
<table class="table is-striped is-narrow is-hoverable is-fullwidth">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>AR Level</th>
</tr>
</thead>
<tbody id="myTable">
</tbody>
</table>
这是JS:
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR")
.get()
.then(
function(querySnapshot){
querySnapshot.forEach(function(doc){
dataObj = doc.data()
console.log(dataObj)
buildTable(dataObj)
function buildTable(data){
var table = document.getElementById('myTable')
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].Title}</td>
<td>${data[i].Author}</td>
<td>${data[i].Points}</td>
</tr>`
table.innerHTML += row
}
}
})
}
)
推荐答案
我不明白为什么在函数中使用for循环.除非一本书"是指文档是一系列包含标题/作者/分数"字段的项目.
I don't see why you're using a for loop in your function. Unless one "Book" document is an Array of items each having the Title/Author/Points fields.
您基本上在遍历数据对象,就好像它是数组一样.可能是,不是.
You're basically looping through the data object as if it's an array. Chances are, it's not.
如果我是对的,则一本书"文档是包含这三个字段的对象/地图,那么您的代码应如下所示:
If I'm right, and one "Book" document is object/map containing those three fields, then your code should be like this:
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR")
.get()
.then(querySnapshot=>{
querySnapshot.forEach(doc=>{
let data = doc.data();
let row = `<tr>
<td>${data.Title}</td>
<td>${data.Author}</td>
<td>${data.Points}</td>
</tr>`;
let table = document.getElementById('myTable')
table.innerHTML += row
})
})
.catch(err=>{
console.log(`Error: ${err}`)
});
这篇关于如何将Firestore文档中的所有数据显示到html表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!