我正在尝试使用javascript将特定数据从Firebase云Firestore数据库发布到我的html网站。该数据库由集合“帖子”和具有自动创建的ID的文档组成。每个文档都有一个字段,该字段包含名为“ User_Email”的用户电子邮件以及实际用户输入的其他字段。我想在HTML网页上仅向用户显示包含他/她当前登录的电子邮件的文档。我使用firebase中提供的用户身份验证来让用户登录。代码附在下面
var db = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
db.settings(settings);
var mainApp = {};
(function(){
var firebase = app_fireBase;
var uid = null;
firebase.auth().onAuthStateChanged(function(user) {
var user = firebase.auth().currentUser;
var name, email, uid, emailVerified;
if (user){
// User is signed in.
uid = user.uid;
name = user.displayName;
email = user.email;
emailVerified = user.emailVerified;
//Welcome message unique per user
//const user_dashboard = document.querySelector("#user_dashboard");
//user_dashboard.innerHTML = "<h> Welcome, " + name + "</h>";
document.getElementById("user_dashboard").innerHTML = "Welcome, "+ name;
//console.log("UID = ", current_uid);
}
else{
// redirect to login page.
uid = null;
window.location.replace("login.html");
}
});
function logOut(){
firebase.auth().signOut();
}
mainApp.logOut = logOut;
mainApp.dataStore = dataStore;
})()
var selectedFile;
$("#file").on("change", function(event){
selectedFile = event.target.files[0];
});
var imageURL;
var imagePath;
function imageUpload(){
//get elements
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
//listen for file selection
fileButton.addEventListener('change', function(e) {
var user = firebase.auth().currentUser;
var uid;
if (user){
// User is signed in.
uid = user.uid;
}
//get file
var file = e.target.files[0];
//create storage ref
var storageRef = firebase.storage().ref(uid + '/' + file.name);
//upload file
var task = storageRef.put(file);
//update progress bar
task.on('state_changed',
function progress(snapshot){
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
},
function error(err){
},
function complete(){
storageRef.getDownloadURL().then(function(url) {
// Insert url into an <img> tag to "download"
imageURL = url;
imagePath = storageRef;
}).catch(function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
// File doesn't exist
break;
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect the server response
break;
}
});
}
);
});
}
document.getElementById('dashForm').addEventListener('submit', dataStore);
function dataStore(e){
e.preventDefault();
const petName = document.querySelector("#petname").value;
const petSpecies = document.querySelector("#petspecies").value;
const petBreed = document.querySelector("#petbreed").value;
const lostLocation = document.querySelector("#lostlocation").value;
const Reward = document.querySelector("#reward").value;
const distinctFeatures = document.querySelector("#DistinctFeatures").value;
const imgSubmit = imageURL;
//const imgPath = imagePath;
//alert(imageURL);
//alert(imgPath);
var user = firebase.auth().currentUser;
var name, email, uid, emailVerified;
if (user){
// User is signed in.
uid = user.uid;
name = user.displayName;
email = user.email;
emailVerified = user.emailVerified;
}
setTimeout(db.collection("Posts").doc().set, 500)
db.collection("Posts").doc().set({
Pet_Name : petName,
Pet_Species: petSpecies,
Pet_Breed : petBreed,
Last_Location : lostLocation,
Reward : Reward,
Distinct_Features : distinctFeatures,
ImageURL : imgSubmit,
User_Email : email,
User_Name : name,
User_UID : uid,
//Image_Path : imagePath
})
$("#postedAlet").show().delay(3000).fadeOut('slow');
setTimeout(location.reload.bind(location), 500)
}
//const posts_div = document.getElementById("#posts_group");
const posts_div = document.getElementById("myTable");
db.collection("Posts").onSnapshot(function(querySnapshot)
{
querySnapshot.docChanges().forEach(function(change)
{
if(change.type === "added")
{
/*posts_div.innerHTML += "<div class ='list-item'><p>Name: " + change.doc.data().Pet_Name + "</p></div>"*/
posts_div.innerHTML += "<tr><td>" + change.doc.data().Last_Location + "</td><td>" + change.doc.data().Pet_Name + "</td><td>" + change.doc.data().Pet_Species + "</td><td>" + change.doc.data().Pet_Breed + "</td><td>" + change.doc.data().Reward + "</td><td>" + change.doc.data().Distinct_Features + "</td><td><img align='right' id='postImage' src='" + change.doc.data().ImageURL + "'/></td><td><a id = found_pet href='mailto:" + change.doc.data().User_Email + "?Subject=[FIND%20MY%20PET]%20Your%20pet%20has%20been%20FOUND' target='_top'>Found " + change.doc.data().User_Name +"'s Pet</a></td></tr>";
}
});
});
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr"),
th = table.getElementsByTagName("th");
// Loop through all table rows, and hide those who don't match the search query
for (i = 1; i < tr.length; i++) {
tr[i].style.display = "none";
for(var j=0; j<th.length-2; j++){
td = tr[i].getElementsByTagName("td")[j];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter.toUpperCase()) > -1){
tr[i].style.display = "";
break;
}
}
}
}
}
#findmypetImg{
background-repeat: no-repeat;
position: left;
}
#formCss{
bottom: 190px;
}
#posts-item{
border: solid thick;
border-color: #37A4EF;
border-radius: 25px;
left: 140px;
margin: 5px;
}
#found_pet{
display: inline-block;
margin-top: 5px;
border: solid;
border-width: 2px;
border-color: #37a4ef;
padding-top: 5px;
padding-bottom:5px;
padding-left: 10px;
padding-right: 10px;
border-radius: 10px;
font-size: 75%;
}
#found_pet:hover{
background: #F5F5F5;
text-decoration: none;
}
#imgSubmit{
color: black;
}
#user_dashboard{
color: black;
font-weight: bold;
bottom: -15px;
}
#postFields{
font-size: 120%;
}
#postImage{
border-radius: 25px;
padding: 20px;
width: 150px;
height: 150px;
}
/* Remove the navbar's default margin-bottom and rounded borders */
.navbar {
margin-bottom: 0;
border-radius: 0;
background-color: #37A4EF;
}
.navbar-inverse .navbar-nav>li>a {
color: #fff;
}
.navbar-brand {
color: #fff !important;
}
/* Set height of the grid so .sidenav can be 100% (adjust as needed) */
.row.content {height: 450px}
/* Set gray background color and 100% height */
.sidenav {
padding-top: 20px;
background-color: #f1f1f1;
height: 100%;
}
.feedSection {
border: 1px solid grey;
border-radius: 4px;
}
/*upload lost pet section styling*/
.contrastHeader {
color:black;
}
input:focus {
outline:none !important;
}
.btn {
background-color: #37A4EF !important;
margin-top: 6px;
}
textarea {
width: 50%;
height: 100px;
padding: 12px 20px;
box-sizing: border-box;
border: 3px solid #37A4EF;
border-radius: 25px;
font-size: 16px;
resize: vertical;
outline:none !important;
}
hr {
padding: 0;
border: none;
height: 1px;
background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));
background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));
background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));
background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));
color: #333;
text-align: center;
}
/* Posts table and Search Filter */
#myInput {
/*background-image: url('/css/searchicon.png'); Add a search icon to input */
background-position: 10px 12px; /* Position the search icon */
background-repeat: no-repeat; /* Do not repeat the icon image */
width: 100%; /* Full-width */
font-size: 16px; /* Increase font-size */
padding: 12px 20px 12px 40px; /* Add some padding */
border: 1px solid #ddd; /* Add a grey border */
margin-bottom: 12px; /* Add some space below the input */
border: 3px solid #37A4EF;
height: 100%;
}
#myTable, #myPostsTable{
border-collapse: collapse; /* Collapse borders */
width: 100%; /* Full-width */
border: 1px solid #ddd; /* Add a grey border */
font-size: 18px; /* Increase font-size */
}
#myPostsTable th, #myPostsTable td, #myTable th, #myTable td {
text-align: left; /* Left-align text */
padding: 12px; /* Add padding */
}
#myPostsTable tr, #myTable tr {
/* Add a bottom border to all table rows */
border-bottom: 1px solid #ddd;
}
#myPostsTable tr.header, #myPostsTable tr:hover, #myTable tr.header, #myTable tr:hover {
/* Add a grey background color to the table header and on hover */
background-color: #f1f1f1;
}
/*--------------------------------------------------------------------------------------*/
input[type=text]{
border: 2px solid #37A4EF;
margin-bottom: 5px !important;
border-radius: 25px;
padding: 20px;
width: 200px;
height: 15px;
}
input[type=number]{
border: 2px solid #37A4EF;
margin-bottom: 5px !important;
border-radius: 25px;
padding: 20px;
width: 200px;
height: 15px;
}
input[type=submit] {
background-color: #37A4EF;
border: none;
border-radius: 25px;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
input[type=file], input[type=text]{
margin: 0 auto;
display: inline-block;
}
/* Set black background color, white text and some padding */
footer {
background-color: #37A4EF;
color: white;
padding: 15px;
}
/* On small screens, set height to 'auto' for sidenav and grid */
@media screen and (max-width: 767px) {
.sidenav {
height: auto;
padding: 15px;
}
.row.content {height:auto;}
}
.imgSubmit{
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head><!-- -->
<title>Find My Pet</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="dashboard.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.8/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-firestore.js"></script>
</head>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li><a href="dashboard.html">Dashboard</a></li>
<li><a href="#posts">Posts</a></li>
<li id="myPosts"><a href="myposts.html">My Posts</a></li>
<li><a href="about.html">About</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li id="user_dashboard"></li>
<li><a href="login.html"><span class="glyphicon glyphicon-log-in"></span> Logout</a></li>
</ul>
</div>
</div>
</nav>
<body id="body">
<img src="images/findmypet.jpg" id="findmypetImg">
<div class="container-fluid text-center">
<div class="row content">
<div class="col-sm-2">
</div>
<div class="col-sm-12 text-center" id="formCss">
<h1 class="contrastHeader" id="dashboard">Dashboard</h1>
<br>
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#register">Collapse Registration</button>
<div id="register" class="collapse in">
<h3 class="contrastHeader">Register Lost Pet</h3>
<form id="dashForm" action="" class="middle">
<input id="petname" name="petname" type="text" placeholder="Pet Name... "/>
<input id="petspecies" autocomplete="on" name="petspecies" type="text" placeholder="Pet Species..."/>
<br>
<input id="petbreed" name="petbreed" type="text" placeholder="Pet Breed..."/>
<input id="lostlocation" name="lostlocation" type="number" placeholder="Last Known Location..."/>
<br>
<input id="reward" name="reward" type="number" pattern="[0-9]" placeholder="Reward (optional)..."/>
<br>
<!--<input id="imgSubmit" class= "imgSubmit" name="petimage" type="file"/>-->
<!-- IMAGE UPLOAD -->
<p>Upload Image below</p>
<progress value="0" max = "100" id = "uploader">0%</progress>
<input type="file" value = "upload" id = "fileButton" onclick= "imageUpload()" placeholder= "Upload Image" accept="image/*"/>
<br><br>
<textarea id="DistinctFeatures"placeholder="Distinct Features..."></textarea>
<br><br>
<button id="submit_btn" class="btn btn-success" type="submit" onclick="dataStore()"> Submit </button>
</form>
<div class="alert alert-success" id="postedAlet" hidden>
<strong>Posted!</strong>
</div>
</div>
<br>
<hr>
<br>
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#collapsePosts">Collapse Posts</button>
<div id="collapsePosts" class="collapse in">
<h3 class="contrastHeader" id="#Posts">Posts</h3>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search...">
<table id="myTable">
<tr class="header">
<th>Last Location</th>
<th>Pet Name</th>
<th>Pet Species</th>
<th>Pet Breed</th>
<th>Reward</th>
<th>Distinct Features</th>
<th>Picture</th>
<th>Contact Owner</th>
</tr>
</table>
</div>
</div>
<div class="col-sm-2">
</div>
</div>
</div>
<br><br>
<footer class="container-fluid text-center">
<p>© 2018 by FindMyPet</p>
</footer>
<!--JS files-->
<script src="fireBase.js"></script>
<script src="dashboard.js"></script>
<script src="login.js"></script>
<script src="animalList.js"></script>
</body>
</html>