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

求助:无法通过HTML/JavaScript读取Firebase实时数据库数据

Firebase实时数据库读取失败:问题分析与修复方案

问题背景

能在Firebase控制台查看实时数据库内的数据,但通过HTML/JavaScript读取时无法获取任何内容,尝试两种实现方式均失败。

数据库结构

https://pump-a559c-default-rtdb.firebaseio.com/
Sensor
  pump1
    Cycle:217
    Duration:4.49222
    GalsPumped:26953.33203
    PumpID:1
    StartTime:"06:09:2022 17:55:39"
  pump2
    Cycle:7
    Duration:0.17806
    GalsPumped:1068.33325
    PumpID:2
    StartTime:"06:09:2022 17:30:03"

第一种实现的问题与修复

原代码问题

  1. DOM元素获取错误:直接使用Start-time这类带减号的变量名,JS会将其解析为减法运算,必须通过document.getElementById()获取元素。
  2. 语法逻辑错误:snapshot.forEach()后直接跟else,forEach没有分支逻辑,应先判断快照是否存在再处理数据。
  3. 数据覆盖问题:遍历两个泵的数据时,会用pump2的内容覆盖pump1的,需区分显示。

修复后代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PUMP Data</title>
    <style>
        body {text-align: center;}
        .pump-details {float: left; width: 50%; background-color: floralwhite; color: darkslategray;}
        input {width: 120px;}
    </style>
</head>
<body>
    <div id="pump1Details" class="pump-details">
        <h1>PUMP1</h1>
        <h3 id="Start-time-1"></h3>
        <h3 id="Cycle-1"></h3>
        <h3 id="Duration-hrs-1"></h3>
        <h3 id="Pumped-gals-1"></h3>
    </div>
    <div id="pump2Details" class="pump-details">
        <h1>PUMP2</h1>
        <h3 id="Start-time-2"></h3>
        <h3 id="Cycle-2"></h3>
        <h3 id="Duration-hrs-2"></h3>
        <h3 id="Pumped-gals-2"></h3>
    </div>

<script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
    import { getDatabase, ref, get, child } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js"

const firebaseConfig = {
  apiKey: "AIzaSyAKQ4cRyBMBbjhsYpg5w96wVj_-qE4zUGw",
  authDomain: "pump-a559c.firebaseapp.com",
  databaseURL: "https://pump-a559c-default-rtdb.firebaseio.com",
  projectId: "pump-a559c",
  storageBucket: "pump-a559c.appspot.com",
  messagingSenderId: "838180391277",
  appId: "1:838180391277:web:df22c7d634310ae135b264"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const dbref = ref(db);

get(child(dbref, "Sensor"))
.then((snapshot) => {
    if (snapshot.exists()) {
        snapshot.forEach((childSnapshot) => {
            const pumpData = childSnapshot.val();
            const pumpId = pumpData.PumpID;
            // 根据泵ID更新对应DOM元素
            document.getElementById(`Start-time-${pumpId}`).innerHTML = `Start-time: ${pumpData.StartTime}`;
            document.getElementById(`Cycle-${pumpId}`).innerHTML = `Cycle: ${pumpData.Cycle}`;
            document.getElementById(`Duration-hrs-${pumpId}`).innerHTML = `Duration-hrs: ${pumpData.Duration}`;
            document.getElementById(`Pumped-gals-${pumpId}`).innerHTML = `Pumped-gals: ${pumpData.GalsPumped}`;
        });
    } else {
        alert("No data found");
    }
})
.catch((error) => {
    alert(error);
});
</script>
</body>
</html>

第二种实现的问题与修复

原代码问题

  1. SDK混用:用了模块化v9 SDK的导入方式,却调用旧版firebase.database()语法,两种写法不兼容。
  2. 导入错误:错误地从firebase-database.js导入getAnalytics,应导入数据库相关方法。
  3. 页面加载事件绑定错误:window.onload(FetchAllData())会立即执行函数,而非在页面加载时触发,正确写法是赋值函数引用。

修复后代码(采用v9模块化写法)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PUMP Data List</title>
    <style>
        body {text-align: center;}
        #list {list-style: none; padding: 0;}
        .pump-item {margin: 20px auto; padding: 15px; background-color: floralwhite; width: 50%;}
    </style>
</head>
<body>
    <ul id="list"></ul>

<script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
    import { getDatabase, ref, get, child } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js";

const firebaseConfig = {
  apiKey: "AIzaSyAKQ4cRyBMBbjhsYpg5w96wVj_-qE4zUGw",
  authDomain: "pump-a559c.firebaseapp.com",
  databaseURL: "https://pump-a559c-default-rtdb.firebaseio.com",
  projectId: "pump-a559c",
  storageBucket: "pump-a559c.appspot.com",
  messagingSenderId: "838180391277",
  appId: "1:838180391277:web:df22c7d634310ae135b264",
  measurementId: "G-K66Z05LFCD"
};

const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

function addItemsToList(starttime, cycle, duration, pumped, pumpId) {
    const ul = document.getElementById('list');
    const pumpItem = document.createElement('li');
    pumpItem.className = 'pump-item';

    pumpItem.innerHTML = `
        <h2>PUMP ${pumpId}</h2>
        <li>Start-time: ${starttime}</li>
        <li>Cycle: ${cycle}</li>
        <li>Duration-hrs: ${duration}</li>
        <li>Pumped-gals: ${pumped}</li>
    `;
    ul.appendChild(pumpItem);
}

async function FetchAllData() {
    const dbref = ref(db);
    try {
        const snapshot = await get(child(dbref, "Sensor"));
        if (snapshot.exists()) {
            snapshot.forEach((childSnapshot) => {
                const data = childSnapshot.val();
                addItemsToList(data.StartTime, data.Cycle, data.Duration, data.GalsPumped, data.PumpID);
            });
        } else {
            alert("No data found");
        }
    } catch (error) {
        alert(error);
    }
}

window.addEventListener('load', FetchAllData);
</script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:25:27