如何显示当前数据而不是获取多个数据。
我想删除以前的数据,因为每当新数据存储在Firebase上时,它就会复制相同的数据大约4次。
我正在使用移动应用程序将数据发送到Firebase。我将databaseref.once
更改为databaseref.on
,因此它可以是实时数据库,但是表中存储了多个数据。
<html>
<head>
<title>Firebase Realtime Database Web</title>
<script>
// firebase config here
</script>
</head>
<body>
<h3>Police Station 1</h3>
<table id="reports" border="1">
<tr>
<th>Email Address</th>
<th>Caption</th>
<th>Location</th>
<th>Time</th>
<th>Picture</th>
</tr>
</table>
<script>
var tblUsers = document.getElementById('reports');
var databaseRef = firebase.database().ref('PP3/');
var rowIndex = 1;
databaseRef.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblUsers.insertRow(rowIndex);
var email = row.insertCell(0);
var caption = row.insertCell(1);
var location = row.insertCell(2);
var time = row.insertCell(3);
var picture = row.insertCell(4);
email.appendChild(document.createTextNode(childData.Email.replace(/\\/g, '').replace(/"/g, '')));
caption.appendChild(document.createTextNode(childData.Caption.replace(/\\/g, '').replace(/"/g, '')));
location.appendChild(document.createTextNode(childData.Location.replace(/\\/g, '').replace(/"/g, '')));
time.appendChild(document.createTextNode(childData.Time.replace(/\\/g, '').replace(/"/g, '')));
picture.appendChild(document.createTextNode(childData.Picture.replace(/\\/g, '').replace(/"/g, '')));
rowIndex = rowIndex + 1;
});
});
</script>
</body>
</html>
答案 0 :(得分:1)
最简单的方法是向表中添加tbody
元素:
<table id="reports" border="1">
<tr>
<th>Email Address</th>
<th>Caption</th>
<th>Location</th>
<th>Time</th>
<th>Picture</th>
</tr>
<tbody id="reportbody"></tbody>
</table>
然后清除,然后再向其中添加数据:
<script>
var tblUsers = document.getElementById('reportbody');
var databaseRef = firebase.database().ref('PP3/');
var rowIndex = 1;
databaseRef.on('value', function(snapshot) {
tblUsers.innerHTML = '';
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblUsers.insertRow(rowIndex);
...
请注意,虽然简单,但这并不是很有效,因此您可能会看到一些闪烁。如果出现问题,请考虑监听Firebase中的child_
事件,该事件可为您提供信息以更精确地更新表,而不是上面的蛮力刷新。