【问题标题】:Connecting Firebase database values to Firebase Web App将 Firebase 数据库值连接到 Firebase Web App
【发布时间】:2017-04-02 15:46:54
【问题描述】:

所以我使用 Google 的 Firebase 构建了一个数据库和一个网络应用程序。数据库和 Web 应用程序都已部署并且都可以工作。我正在尝试使用 HTML 和 javascript 从数据库中读取值。对于我尝试的两种不同方式,在我的网页上显示的值为 null。我附上了保存在数据库中的值的图片。

<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js">      
</script>
<script>
// Initialize Firebase
     
var config = {  
   apiKey: "AIzaYUIYUkokngctrIbR9krB6Do",
   authDomain: "HelloWorld.firebaseapp.com",
   databaseURL: "https://HelloWorld.firebaseio.com/",
   storageBucket: "HelloWorld.appspot.com",
   messagingSenderId: "8298539696" 
}; 

  //This was the first was we tried to do it 
  firebase.initializeApp(config);
  //var rootRef = firebase.database().ref();
  //var dist = rootRef.child("dalemccaugh");
  var ref = firebase.database().ref();
  ref.once("value")
   .then(function(snapshot) {
    var test = snapshot.child("dalemccaugh").val(); 

      console.log(test);
});

//The was the second way we tried
    function printData() {
//console.log(dist)
    dist.on("value", function(snapshot) {
        console.log(snapshot.val());
    }, function(errorObject) {
        console.log("The read failed: " +errorObject.code);
    });

}
</script>

【问题讨论】:

  • 如果快照值在您的thenon 回调中记录为null,则您正在检查的位置没有值。
  • 您检查过控制台是否有错误 - 可能 firebase 没有正确初始化...

标签: javascript html firebase firebase-realtime-database


【解决方案1】:

“dalemccaugh”是您的数据库的名称。这意味着它是 JSON 层次结构的根。例如,如果您想读取“测试”对象,您可以这样做:

var ref = firebase.database().ref();

ref.child("test").once("value").then(function(snapshot) {
    var test = snapshot.val(); 
    console.log(test);
});

如果您想在根级别读取 JSON 对象,您只需从引用中删除 .child("test")

【讨论】:

    【解决方案2】:

    这是一种引用 Firebase 数据库并检索数据的方法。

    var ref = firebase.database().ref();
    ref.on('child_added', function(snapshot){
            var data = snapshot.val();
    });
    

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2019-04-27
      • 2020-02-24
      • 2018-04-30
      • 1970-01-01
      • 2019-06-28
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多