【问题标题】:Issues with retrieving Firebase data into a textbox in html page将 Firebase 数据检索到 html 页面中的文本框中的问题
【发布时间】:2017-04-14 15:18:44
【问题描述】:

// Calls the onClick command from the Populate Button
function myFunctionPopulate() {

// Creates a new Firebase reference linking this JS to the Firebase database
var ref = new Firebase("https://project01-d018e.firebaseio.com/Numbers");

// Creates a snapshot of the data from the desired Firebase database and adds it to 'value' 
ref.on('value', function(snapshot) {

// Adds a console log of the data recived from Firebase
console.log(snapshot.val());

// Creates a variable called data to which the snapshot is saved
var data = snapshot.val();

for (var key in data) {
  
  if (data.hasOwnProperty(key)) {

    // Takes the id of the textbox and adds a value of (data[key]) where data = snapshot.val() which is the snapshot of the data
    document.getElementById('id1').value=(data[key]);

    // Adds a console log message to confirm the textbox has been populated
    console.log('Value Added');
    };
    // End of if
  }
  // End of for
});
// End of ref.on
}
// End of function
<div id="button">
  <button id="RButton" value="submit" onclick="myFunctionPopulate()">Populate</button>
</div>

<div id="button2">
  <button id="RButton" value="submit" onclick="myFunctionClear()">Clear</button>
</div>

<div id="textBox">
  <form>
  From Firebase<br>
  <textarea rows="4" cols="50" id="id1"></textarea>
</form>
</div>

我最近开始使用 Google Firebase 作为存储数据的存储解决方案。到目前为止一切顺利 - 我喜欢它!

但是,我正在尝试将 Firebase 数据库中的数据显示到我的 HTML 网站中,该网站由 2 个按钮和一个文本区域组成。 1个按钮用于填充文本区域,另一个用于清除。目前非常简单的东西。

目前,当我点击填充按钮时,onClick 函数会执行这段 JS:

JS Screenshot

****项目名称已更改为仅供示例****

数字 - 此 JS 引用的数字 - 在 Firebase 控制台中如下所示:

Firebase Console Screenshot

当我点击填充按钮时,文本区域会填充到 HTML 中,但是,只显示来自 Numbers 的最后一条数据,而不是整个列表。

如果可能,我希望将所有数据显示到此文本区域中。

如果有人能对此有所了解,我将不胜感激 - 我不确定这个问题是否与 JS 的“关键”部分有关,因为我不确定这实际上是做什么的 - 这是一个来自 GitHub 的工作片段,我已对其进行了调整以适合我的工作。

我现在已经附加了 JS 和 HTML,虽然它不会工作,因为它不包含 firebase 脚本标签或 firebase 初始化标签,但希望有文本可以使其更清晰

提前谢谢你, G

【问题讨论】:

  • 不要发布文本截图,而是发布实际文本。对于 JSON,您可以通过单击 Firebase Database console 中的“导出 JSON”链接来获取此信息。
  • 我不完全确定在哪里可以找到导出 JSON。我的应用没有托管是否会有所不同?
  • 我已经更新了帖子 - 希望这些更改可能会有所帮助

标签: javascript html firebase firebase-realtime-database


【解决方案1】:

您只看到最后一条数据的原因是您在 for 循环的每次迭代中都替换了 textarea 的内容,而不是附加它。运行以下代码 sn-p 作为示例。在 textarea id1 我正在做你正在做的事情,在 textarea id2 我正在附加到当前值而不是替换它。

var data = ['first','second','third'];

for (var key = 0; key < data.length; key++) {
	document.getElementById('id1').value = data[key]
  document.getElementById('id2').value += data[key]
}
<textarea id="id1"></textarea>
<textarea id="id2"></textarea>

【讨论】:

  • 杰夫你是个传奇!如此简单的修复!希望我能投票,但我的代表不够高.. 但还是谢谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多