无法从firebase获取数据到我的html页面

时间:2016-05-18 17:32:27

标签: javascript html firebase

基本上我想将我的firebase帐户中的数据显示到我的html div元素,但由于div保持空白,我无法这样做。 我是firebase和javascript的初学者,所以请耐心等待。 这是我写的代码。

<div class="content">
    <h1>Dashboard</h1>
    <p>Just DO it!</p>  
    <div id="box">
        <div class="box-top">Bookings</div>
        <div class="box-panel">
            <script>

                var ref = new Firebase("https://fiery-torch-164.firebaseio.com");
                ref.on('value', function(snapshot) {
                  console.log(snapshot.key());
                  document.write(snapshot.key());
                });

            </script>
        </div>
    </div>
</div>

Here is the screenshot of my firebase.

1 个答案:

答案 0 :(得分:2)

目前,您正在打印根节点的密钥,该密钥为null。您可以打印子节点的密钥,例如/days

var ref = new Firebase("https://fiery-torch-164.firebaseio.com/days");
ref.on('value', function(snapshot) {
    console.log(snapshot.key());
    document.write(snapshot.key());
});

为了演示,您可以使用javascript&#39; s迭代对象属性。

ref.on('value', function(snapshot) {
  console.log(snapshot.key());
  var data = snapshot.val();
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      document.write(data[key].name + "<br>");
    };
  }
});

JSFiddle:https://jsfiddle.net/bhn139ep/

使用嵌套循环访问子节点。请参阅JSFiddle以获取更新。

https://jsfiddle.net/bhn139ep/3/

var ref = new Firebase("https://fiery-torch-164.firebaseio.com/days");
ref.on('value', function(snapshot) {

var data = snapshot.val();

//Show Days of week.
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        document.write(data[key].name + "<br>");
    };
}
document.write('<br><br>');

//Show Slots for each day of week using a nested for in loop.
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        var slots = data[key].slots;
        var dayOfWeek = data[key].name;

        for (var slotKey in slots) {
            if (slots.hasOwnProperty(slotKey)) {

                //Get an individual slot.
                var slot = slots[slotKey];

                console.log(slot);
                document.write('Day of week: ' + dayOfWeek + '<br>');
                document.write('Slot Time: ' + slot.time + '<br>');
                document.write('Booked: ' + slot.booked + '<br>');
                document.write('<hr>');
            }
        }                              
    }
}

//Access data within a node directly.
console.log(data['monday'].name); //Prints Monday.
console.log(data['tuesday']['slots']['72'].booked); //prints false.
console.log(data.tuesday.slots['72'].booked); //prints false.

});