Realtime Update between Firebase and HTML Table

醉酒当歌 提交于 2019-12-22 01:22:24

问题


Below code displays data from firebase into table

<html>
    <head>
    </head>
    <body >
    
    <table style="width:100%;width:100%;" id="ex-table">
      <tr id="tr">
        <th>Brand</th>
       <th>Description</th>
       <th>Item Code</th>
       <th>Product Category</th>
     </table> 
    
    
    
    
    
    <script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      // Initialize Firebase
      var config = {
        apiKey: "AIzaSyB5aqeEmEIB56IvRt4DL8RyOr0JX5Mw3HQ",
        authDomain: "tp-firebase-fd827.firebaseapp.com",
        databaseURL: "https://tp-firebase-fd827.firebaseio.com",
        projectId: "tp-firebase-fd827",
        storageBucket: "tp-firebase-fd827.appspot.com",
        messagingSenderId: "191127646247"
      };
      firebase.initializeApp(config);
      
       var database = firebase.database();
        database.ref().once('value', function(snapshot){
            if(snapshot.exists()){
                var content = '';
                snapshot.forEach(function(data){
                    var val = data.val();
                    content +='<tr>';
                    content += '<td>' + val.brand + '</td>';
    				content += '<td>' + val.description + '</td>';
    				content += '<td>' + val.item_code + '</td>';
    				content += '<td>' + val.prod_cat + '</td>';
                    content += '</tr>';
                });
                $('#ex-table').append(content);
            }
        });
      
      
     </script>
     
     
     
     
    
    
    </body>
    </html>

However it doesnt change automatically when i change data in my firebase. How can i achieve realtime update? Thats the only thing i need to do. TYSM for future help


回答1:


you used the "once" method that listens for changes once and then stops. you want to use the "on" method that keeps listening for changes. for example, instead of:

database.ref().once('value', function(snapshot){

use:

database.ref().on('value', function(snapshot){

relevant documentation: https://firebase.google.com/docs/database/web/read-and-write#listen_for_value_events



来源:https://stackoverflow.com/questions/45024326/realtime-update-between-firebase-and-html-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!