javascript 无法使用html从firebase读取数据

t40tm48m  于 2022-10-30  发布在  Java
关注(0)|答案(2)|浏览(154)

我可以从控制台看到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"

先道:

<!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>Document</title>
    <style>
        body {text-align: center;}
        #findDetails {float: left; width: 50%; background-color: floralwhite; color: darkslategray;}
        input {width: 120px;}
    </style>
</head>
<body>

    <div id="findDetails">
        <h1>PUMP1</h1>

        <h3 id="Start-time" type="text"></h3>
        <h3 id="Cycle" type="text"></h3>
        <h3 id="Duration-hrs" type="text"></h3>
        <h3 id="Pumped-gals" type="text"></h3> <br><br>
    </div>

<script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
    import {getDatabase, ref, get, set, child, update, remove} 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);

  // Initialize the database
  const db = getDatabase(app);

  const dbref = ref(db);

    get(child(dbref, "Sensor"))
    .then((snapshot)=>{
        snapshot.forEach((child)=>{
            Start-time.innerHTML = "Start-time: " + child.val().StartTime;
            Cycle.innerHTML = "Cycle: " + child.val().Cycle;
            Duration-hrs.innerHTML = "Duration-hrs: " + child.val().Duration;
            Pumped-gals.innerHTML = "Pumped-gals: " + child.val().GalsPumped;
     //       console.log(child.val().StartTime);
        } else {
            alert("No data found");
        }
    })
    .catch((error)=>{
        alert(error);
       });

    </script>
</body>
</html>

老二道:

<!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>Document</title>
    <style>
        body {text-align: center;}
        #findDetails {float: left; width: 50%; background-color: floralwhite; color: darkslategray;}
        input {width: 120px;}
    </style>
</head>
<body>

<ul id="list">

</ul>

<script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js";
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries

    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-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"
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);

        var pumpId=0;
        function addItemsToList(starttime,cycle,duration,pumped){
            var ul=document.getElementById('list');
            var header= document.createElement('h2');

            var _starttime= document.createElement('li');
            var _cycle= document.createElement('li');
            var _duration= document.createElement('li');
            var _pumped= document.createElement('li');

            _starttime.innerHTML='Start-time: '+starttime;
            _cycle.innerHTML='Cycle: '+cycle;
            _duration.innerHTML='Duration-hrs: '+duration;
            _pumped.innerHTML='Pumped-gals: '+pumped;

            ul.appendChild(header);
            ul.appendChild(_starttime);
            ul.appendChild(_duration);
            ul.appendChild(_pumped);
        }

        function FetchAllData(){
            firebase.database().ref('Sensor').once('value',function(snapshot){
                snapshot.forEach(
                    function(ChildSnapshot){
                        let start = ChildSnapshot.val().StartTime;
                        let cycle = ChildSnapshot.val().Cycle;
                        let duration = ChildSnapshot.val().Duration;
                        let pumped = ChildSnapshot.val().GalsPumped;
                        addItemsToList(start,cycle,duration,pumped);
                    }
                );
            });
        }
        window.onload(FetchAllData());

</script>

</body>
</html>
oxf4rvwz

oxf4rvwz1#

您正在加载整个Sensor节点,这意味着您将获得一个包含所有传感器数据的snapshot。要获得每个特定传感器的数据,您需要循环访问该快照中的子节点。
因此:

get(child(dbref, "Sensor")
.then((snapshot)=>{
    snapshot.forEach((child)=>{
        Start-time.innerHTML = "Start-time: " + child.val().StartTime;
        Cycle.innerHTML = "Cycle: " + child.val().Cycle;
        Duration-hrs.innerHTML = "Duration-hrs: " + child.val().Duration;
        Pumped-gals.innerHTML = "Pumped-gals: " + child.val().GalsPumped;
    });
})
.catch((error)=>{
    alert(error);
});

更新:代码中的Start-time和其他变量未定义,并且在许多情况下不是有效的变量名称。如果要从DOM访问元素,需要通过调用document.getElementById("Start-time")获取该元素,然后在其结果上调用innerHMTL

例如:

get(child(dbref, "Sensor")
.then((snapshot)=>{
    snapshot.forEach((child)=>{
        document.getElementById("Start-time").innerHTML = "Start-time: " + child.val().StartTime;
        ...
    });
});
wqsoz72f

wqsoz72f2#

下面的代码解决了这个问题,现在我得到了我的传感器数据:

get(child(dbref, "Sensor"))
.then((snapshot)=>{
    snapshot.forEach((child)=>{
        id_PumpID.innerHTML = "Pump ID: " + child.val().PumpID
        id_StartTime.innerHTML = "StartTime: " + child.val().StartTime;
        id_Cycle.innerHTML = "Cycle: " + child.val().Cycle;
        id_Duration.innerHTML = "Duration: " +  child.val().Duration;
        id_GalsPumped.innerHTML ="GalsPumped: " + child.val().GalsPumped;
    })
});

相关问题