2016-11-18 26 views
2

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

<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> 

enter image description here

+0

如果快照值在您的'then'或'on'回调中被记录为'null',那么在您检查的位置没有值。 –

+0

您是否检查过控制台是否有错误 - 可能firebase未正确初始化... – jcuenod

回答

3

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

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

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

如果你想读在根级别的JSON对象,你只需要删除.child(”测试“)从您的参考。

0

以下是您可以引用Firebase数据库并检索数据的方法。

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