2017-04-18 91 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

相關問題