2017-04-18 85 views
0

我正在开发一个简单的用户注册Web应用程序,它将nameemail作为用户的输入。使用Firebase作为在线数据存储。如何将Firebase中的数据转换为HTML页面?

JavaScript文件:(使用的JQuery)

databaseRef.orderByKey() 
    .once('child_added', function(snapshot) { 
    snapshot.forEach(function(childSnapshot) { 

     var childKey = childSnapshot.key; 
     var childData = childSnapshot.val(); 

     console.log("Key: " + childKey + "; Value: " + childData); 

     $('#nameValue').text(childData); 
     $('#emailValue').text(childData); 
    }); 
    }); 

HTML代码:

<div class="table-responsive"> 
     <table class="table"> 
      <thead> 
       <tr> 
        <th>Name</th> 
        <th>Email</th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr> 
        <td id='nameValue'></td> 
        <td id='emailValue'></td> 
       </tr> 

      </tbody> 
     </table> 
    </div> 
    </div> 

这是我在火力地堡的数据库结构。

users 
    | 
    -KhyubUqLRGUGW-rtija 
     |--- email: "[email protected]" 
     |--- name: "p1" 

我可以在浏览器控制台上获取这些值。

Key: email; Value: [email protected] 
Key: name; Value: p1 

但我无法在我的HTML页面上显示它们。我的JQuery函数可以做些什么来显示我的HTML页面上的内容。

这是当我提交详细信息时得到的当前输出。

enter image description here

回答

2

首先使用

$('#nameValue').append(childKey); 
$('#emailValue').append(childData); 

,而不是

$('#nameValue').text(childKey); 
$('#emailValue').text(childData); 

.text()取代每次调用一次,即它覆盖以前的数据,您需要被追加什么文本数据到以前的数据。

其次,您在将数据附加到表格时犯了一个错误。你应该做的是:

$("#data").append('<tr><td>' + childKey + '</td><td>'+ childData+'</td></tr>'); 

在你更新的HTML代码:

<div class="table-responsive"> 
     <table class="table"> 
      <thead> 
       <tr> 
        <th>Name</th> 
        <th>Email</th> 
       </tr> 
      </thead> 

       <tbody id="data"> <!-- changed --> 

      </tbody> 
     </table> 
    </div> 
    </div> 

注意,因为追加它会导致不正确的HTML表结构后,我已删除了你..线。这是结构你想W3school example 现在会正确地追加到表列

+0

这非常接近!但是,然后,输出是'[email protected] p1'作为我的第一个表数据。我们如何改进这一点? – Chip

+0

细化为?你想在这里实现什么? – warl0ck

+0

我有两列。 'name'和'email'。但结果只会附加在'name'列中。那么,现在我怎样才能让他们分开。每个值在不同的列中。 – Chip

1

而是在你的表的<th>硬编码固定值,你可以指定keys,在你的数据库中。你甚至可以对表格的数据做同样的事情。即values与那些各自的keys

修改你的HTML代码如下:

<div class="table-responsive"> 
    <table class="table"> 
    <thead> 
     <tr id="keysRow"></tr> 
    </thead> 
    <tbody> 
     <tr id="valuesRow"></tr> 
    </tbody> 
    </table> 
</div> 

这是你如何从你的火力地堡中的数据。

databaseRef 
    .once('child_added', function(snapshot) { 
    snapshot.forEach(function(childSnapshot) { 

     var childKey = childSnapshot.key; 
     var childData = childSnapshot.val(); 

     console.log(childKey + " - " + childData); // Displays key with its value in your Browser Console 

     $('#keysRow').append('<th>' + childKey + '</th>'); 
     $('#valuesRow').append('<td>' + childData + '</td>'); 

    }); 
    }); 
+0

这就是我想要的。但是,当我提交新的提交时,这些值会并排增加。 – Chip

相关问题