如何在不刷新Firebase的情况下实时更新网页?
问题描述:
这是使用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>
答
由于火力点采用独特的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();
的路径为 “PROD_ID /统计/数量”。工作正常。 – hbbz040
很高兴帮助你。 – Ridwan