简体   繁体   English

如何使用 JavaScript 从 web 中的 firebase 检索数据

[英]How to retrieve data from firebase in web with JavaScript

I have buttons similar to the one here A3.我有类似于这里 A3 的按钮。 I want to check the availability of the seat from my database and do accordingly in the if loop.我想从我的数据库中检查座位的可用性,并在 if 循环中进行相应的操作。 But none of my functions below the firebase reference is working.但是我在 firebase 参考下的功能都没有工作。

My database is我的数据库是

My web (app)
     |
    Seats(node)
        |
      Status (node)
           |
          A1 - available (value)
          A2 - available (value)
          A3 - available (value)
          A4 - available (value)

And my js script is我的js脚本是

function A3(){
  var newseat = document.getElementById("A3");
  var firebaseStatusRef = firebase.database().ref().child("Status"); 
  var firebaseSeatStatusRef = firebaseStatusRef.child("A3");

  firebaseSeatStatusRef.on('child_added', snap => {
    var seatStatus = snap.val();
  });

if (firebaseSeatStatusRef=="available") {
  newseat.className="booked-seat";
  newseat.setAttribute("class" , "booked-seat");
  firebaseStatusRef.child("A3").set("booked");
  var fill = newseat.value;
document.getElementById("fill").value += fill + " ";
Seat();

} else  {

  newseat.style.backgroundColor = 'seat';
  newseat.setAttribute("class" , "seat");
  var fill = newseat.value;
document.getElementById("fill").value -=  fill + " ";
BookedSeat();

}

} }

Your check boils down to:您的支票归结为:

var firebaseStatusRef = firebase.database().ref("Seats/Status");
var firebaseSeatStatusRef = firebaseStatusRef.child("A3");
if (firebaseSeatStatusRef=="available") {

This makes no sense in the Firebase Realtime Database API, as you're not reading the value from the database yet.这在 Firebase 实时数据库 API 中没有意义,因为您还没有从数据库中读取值。 To do this, you'll need to attach a listener, and then check the snapshot that you get against the value.为此,您需要附加一个侦听器,然后根据该值检查您获得的快照。 Something like:就像是:

firebaseSeatStatusRef.on('value', snap => {
  var seatStatus = snap.val();
  if (seatStatus == "available") {
    ...
  }
});

Note that any code that needs access to the data from the database must be inside the callback block.请注意,任何需要访问数据库数据的代码都必须回调块内。

This is fairly basic interaction with the Firebase Realtime Database, so you'd do well to study the Firebase documentation on reading values , and possibly taking the Firebase codelab .这是与 Firebase 实时数据库的相当基本的交互,因此您最好研究有关读取值Firebase 文档,并可能参加Firebase 代码实验室

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM