2017-07-07 112 views
1

这里是我的数据库结构(红色我的意见):如何火力地堡数据库中检索值,并将其插入到HTML

enter image description here

的目的是要表明一个简单的网页,照片之旅。我正尝试在此数据库中为每次旅行照片检索“photourl”值。

这里是我的html代码:

<div class="main"> 

     <div class="spot"> 

     <img id="image" height="400" width="400"/> 

     </div> 

    </div> 

    <p><script>document.write(userid);</script></p> 
    <p><script>document.write(tripid);</script></p> 
    <p><script>document.write(photourl);</script></p> 

最后3行只是这里要说明的变量是否有任何值(当我尝试我的HTML代码,它不显示任何)。

我的javascript代码:

//Get User ID and Trip ID in URL 

function GetURLParameter(sParam) 
{ 
var sPageURL = window.location.search.substring(1); 
var sURLVariables = sPageURL.split('&'); 
for (var i = 0; i < sURLVariables.length; i++) 
{ 
    var sParameterName = sURLVariables[i].split('='); 
    if (sParameterName[0] == sParam) 
    { 
     return sParameterName[1]; 
    } 
} 
} 
    var userid = GetURLParameter('userid'); 
    var tripid = GetURLParameter('tripid'); 

//Get image from database 

var database = firebase.database(); 
return firebase.database().ref('/photos/' + userid + 'trips' + 
tripid).once('photourl').then(function(insert) 
{ 
document.getElementsById('image').src = photourl; 
}); 

我的URL会是这样,那么:https://travelertest-e316f.firebaseapp.com/?userid=11K47L3qgUOateC4LGSE29Un2W53&tripid=-Kiv3kukHYLMVefSGPqZ

我不知道如何使它工作,以便检索所有“photourl”值不关于旅行中有多少照片。我不知道如何在简单的HTML页面上显示它们,以便页面显示与旅行中一样多的照片。

谢谢!

回答

0

您可以在行程目标迭代,并获得photourls在数组中:

// add a return statement here if you'll use it as a function 
database.ref(`photos/${userId}/trips/${tripId}`).once('value') // will return you all the photo objects inside the `tripId` 
.then(photosSnap => { 
    const photosObj = photosSnap.val(); 
    const photosUrl = Object.keys(photosObj).map(key => photosObj[key].photourl); 
    // then you can return the array or use it here; 
    console.log(photosUrl); // will be an array of all the photourls 
}).catch(err => alert(err));