我试图创建一个由我在FireBase中创建的表填充的简单表。我是FireBase的新手,我通常在mySQL中工作,并使用php和SQL的组合从数据库中提取。我当前的JSON结构是{
"board1" : {
"c0" : "0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0",
"c1" : "0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0",
"c2" : "0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0",
"c3" : "0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0",
"c4" : "0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0",
"c5" : "0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0",
"c6" : "0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0",
"c7" : "0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0"
}
}
我正在寻找一种方法来检索特定单元格的值,例如c3和数组中的第三项,并将其存储为javascript变量。我在FireBase上找到的每个例子都是复杂而破碎的。谢谢你的帮助!
var database = firebase.database();
var i;
var j;
for (i = 0; i < 7; i++) {
for (j = 0; j < 6; j++) {
var R = i.toString();
var C = j.toString();
var id = C.concat("",R);
var col = "c"+R
var x = piece(i,j);
document.getElementById(id).innerHTML = x;
}
function piece(i,j) {
var C = j.toString();
var col = "c"+C
return database.ref('board1/'col).once('value').then(function(snapshot) {
console.log(snapshot.val());
var piece = snapshot.val()[i];
console.log(piece);
});
});
}
}
&#13;
答案 0 :(得分:1)
如果您想使用实时数据库,您可以执行以下操作。只需在html页面中复制粘贴,使配置值与项目一致,然后使用浏览器打开它。
在打开时,它会将c0
数组写入board1
节点。然后,通过控制台手动修改C03的值,然后单击按钮&#34;读取数据&#34;。
所以这是一个解决方案。但是,您应该阅读此Firebase博文:https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-database.js"></script>
</head>
<body>
<button id="myBtn">Read data</button>
<script>
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: ""
};
firebase.initializeApp(config);
var db = firebase.database();
var newQuoteKey = db.ref('board1/').push().key;
var updates = {};
updates['c0'] = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};
db.ref('board1/').update(updates);
document.getElementById("myBtn").addEventListener("click", function(){
return db.ref('board1/c0').once('value').then(function(snapshot) {
console.log(snapshot.val());
var c03 = snapshot.val()[3];
console.log(c03);
});
});
</script>
<body>
</html>
编辑问题(添加代码)并在 下添加评论后编辑
我会按如下方式重构您的代码(未经过测试,只是&#34;高级&#34;重构,没有所有细节):var database = firebase.database();
var i;
var j;
var promises = [];
for (i = 0; i < 7; i++) {
for (j = 0; j < 6; j++) {
var C = j.toString();
var col = "c" + C;
promises.push(return database.ref('board1/' + col).once('value'));
}
}
var promiseAll = Promise.all(promises);
promiseAll.then(function(results) {
//Here, result items in the results array
//are ordered in the same order they were pushed to the promises array
for (index = 0; index < results.length; ++index) {
console.log(results[index]);
//Do something with the data
//You will have to write the correct code to find back the i,j couples
}
})