【问题标题】:Displaying data from Firebase Database into an html document将 Firebase 数据库中的数据显示到 html 文档中
【发布时间】:2020-12-12 11:02:33
【问题描述】:

我正在尝试将 Firebase 数据库中的数据显示到 html 文档中。在下面你可以看到我的 HTML 和 JavaScript 文件。我对 Firebase 很陌生,所以我很可能犯了一个错误。感谢所有答案!

提前致谢!

HTML:

<p id="profile"></p>

<table id="profiledetails-table">
    <tr id="tr">
        <th>Name</th>
        <th>Email</th>
    </tr>
</table>

Javascript:

firebase.auth().onAuthStateChanged(function(user) {
    var docRef = db.collection('users').doc(firebase.auth().currentUser.uid)

    docRef.get().then(function(snapshot) {
        if (doc.exists) {
            console.log("Document data:", doc.data());

            $('#profiledetails-table').append(doc.data);

        } else {
            console.log("No such document!");
        }
    }).catch(function(error) {
      console.log("Error getting document:", error);
    })
});

【问题讨论】:

    标签: javascript html firebase firebase-realtime-database


    【解决方案1】:

    您正在尝试使用未定义的变量(并且您的编辑器/IDE 应该警告您):您正在使用 if (doc.exists) 但未定义 doc,因此 doc.exists 将始终未定义或您必须在您的开发工具中有一些“无法读取存在未定义的属性”的错误。

    这是您可能想要的方式:

    firebase.auth().onAuthStateChanged(function(user) {
        var docRef = db.collection('users').doc(firebase.auth().currentUser.uid)
    
        docRef.get().then(function({ doc }) {
            if (doc.exists) {
                console.log("Document data:", doc.data());
    
                $('#profiledetails-table').append(doc.data);
    
            } else {
                console.log("No such document!");
            }
        }).catch(function(error) {
          console.log("Error getting document:", error);
        })
    });

    我不太了解 jQuery,所以我不能确定您将数据附加到表的方式是否存在错误,所以如果这不起作用,您可能想看看它。

    【讨论】:

      【解决方案2】:

      正如@Camille 所说,您需要使用 snapshot.exists 和 snapshot.data()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-15
        • 2017-07-29
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        • 2018-09-14
        • 2021-02-08
        • 1970-01-01
        相关资源
        最近更新 更多