2017-09-15 64 views
1

這是使用Firebase的網絡應用程序html代碼。目標是實時檢索數量,而無需刷新/重新加載頁面。如何在不刷新Firebase的情況下實時更新網頁?

怎麼辦? Thxs。

<!DOCTYPE html> 
<html lang="en"> 
<head><meta charset="utf-8"></head> 
<body> 
    <span class="qty" id="qty">0</span> 
    <script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script> 
    <script> 
     var config = { ... }; 
     firebase.initializeApp(config); 
    </script> 
    <script> 
     var dbRef = firebase.database().ref(); 
     var startListening = function() { 
      dbRef.on('child_added', function(snapshot) { 
       var warehouse = snapshot.child("prod_id/stats").val(); 
       document.getElementById("qty").innerHTML = warehouse.qty 
      }); 
     } 
     startListening(); 
    </script> 
</body> 
</html> 

回答

1

由於火力點採用獨特的ID數據,當您參考類似warehouse.qty,並採用child_added代替value,你可能會結束與null數據,因爲路徑是不正確的。

首先檢查您的數據存儲在哪裏。檢查路徑。它在prod_id/stats/qty?或prod_id/stats/<some-unique-key>/qty

如果它在prod_id/stats/qty中,您可能需要將child_added更改爲value。如在下面的代碼:

var dbRef = firebase.database().ref(); 
var startListening = function() { 
    dbRef.on('value', function(snapshot) { 
     var warehouse = snapshot.child("prod_id/stats").val(); 
     document.getElementById("qty").innerHTML = warehouse.qty 
     }); 
} 
startListening(); 
+0

的路徑爲 「PROD_ID /統計/數量」。工作正常。 – hbbz040

+0

很高興幫助你。 – Ridwan

相關問題