从简单博客的firebase快速入门模板分支(来源:https://github.com/firebase/quickstart-js/tree/master/database)
我正在成功地将数据写入firebase数据库,并且能够拉取并显示HTML元素中的所有值,条形码已经开始返回未定义的值,尽管DB / .json中有数据。
用于将数据写入DB的代码示例:
// [START write_fan_out]
function writeNewPost(uid, username, picture, title, body) {
var postedDate = moment().format('DD/MM/YYYY');
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
authorPic: picture,
posted: postedDate,
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
//updates['/category/' + title + '/' + newPostKey] = postData;
//updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
// [END write_fan_out]
这没有问题。以.json格式写的数据示例:
"-KTmYfts6vYEjyjo1rvk" : {
"author" : "Nathan",
"authorPic" : "https://lh4.googleusercontent.com/photo.jpg",
"body" : "Time: 6:00pm\nDuration: 35 seconds\nRecovery: 60 seconds\n",
"posted" : "11/10/2016",
"title" : "Seizure",
"uid" : "rB4n3ELLnFUCWHztHLGA4mVeSHm1"
}
这是正确的数据,因为日期显示在"已发布的"标签。 在页面上呈现的代码是:
function createPostElement(postId, title, text, author, authorId, authorPic, posted) {
var uid = firebase.auth().currentUser.uid;
var html =
'<div class="post mdl-cell mdl-cell--12-col ' +
'mdl-cell--12-col-tablet mdl-cell--4-col-desktop mdl-grid mdl-grid--no-spacing">' +
'<div class="mdl-card mdl-shadow--2dp">' +
'<div class="mdl-card__title dark-purple mdl-color-text--white">' +
'<h4 class="mdl-card__title-text"></h4>' +
'</div>' +
'<div class="header">' +
'<div>' +
'<div class="avatar"></div>' +
'<div class="username mdl-color-text--black"></div>' +
'</div>' +
'</div>' +
'<div class="date"></div>' +
'<div class="text"></div>' +
'</div>' +
'</div>';
// Create the DOM element from the HTML.
var div = document.createElement('div');
div.innerHTML = html;
var postElement = div.firstChild;
componentHandler.upgradeElements(postElement.getElementsByClassName('mdl-textfield')[0]);
// Set values.
postElement.getElementsByClassName('text')[0].innerText = text;
postElement.getElementsByClassName('mdl-card__title-text')[0].innerText = title;
postElement.getElementsByClassName('date')[0].innerText = posted;
postElement.getElementsByClassName('username')[0].innerText = author || 'Anonymous';
postElement.getElementsByClassName('avatar')[0].style.backgroundImage = `url("${authorPic || './silhouette.jpg'}")`;
这适用于每个领域,但是已发布&#34;返回&#39; undefined&#39;尽管数据库中有数据。
代码块的道歉,每个写入,数据库数据和存在都与为什么这不起作用有关,我假设......
我已经测试了&#34;发布了&#34;另一个字段中的数据,并正确显示。我还在&#39; date&#39;中使用了其他字段数据。 div也正常工作。 所以在从数据库中提取到在页面上书写的某个地方,我已经打破了它。