我看过以前的帖子、文档和其他资源,但我就是想不出如何在单击按钮时向我的 firebase 数据库添加条目。该按钮调用 writeNewPost()。这是我试过的
<button type="submit" class="btn btn-light" onclick="writeNewPost()">Submit</button>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase.js"></script>
<script>
var config = {
apiKey: MYAPIKEY,
authDomain: MYDOMAIN,
databaseURL: MYURL,
projectId: MYPROJECT,
storageBucket: STORAGEBUCKET,
messagingSenderId: SENDERID
};
firebase.initializeApp(config);
</script>
<script>
function writeNewPost() {
var postData = {
"Name": "Brett"
};
var newPostKey = firebase.database().ref().push().key;
var updates = {};
updates['/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
</script>
我想要的只是在根目录下有 "Name":"Brett"。
最佳答案
您的代码看起来相当不错。为了让您与 Firebase 进行简单的通信,您首先需要设置一些规则 https://firebase.google.com/docs/database/security/quickstart
P.S:使用了您的代码,将规则添加到 Database → Rules(Tab)
中并且它有效。
Disclaimer!! use the below only for a limited test period of time - since it opens your database to the public - And read always the warnings that might appear in the panel!
{
"rules": {
".read": true,
".write": true
}
}
来自docs :
It is essential that you configure these rules correctly before launching your app to ensure that your users can only access the data that they are supposed to.
您呈现代码的方式 - 内联 onclick=
指向一个仅在代码中稍后定义的函数 - 因此您有可能被未定义
。
将 JS 放在一个地方的更好方法。
删除内联 onclick
并添加 ID
选择器,如 id="submitPost"
<button id="submitPost" type="submit" class="btn btn-light">Submit</button>
比在你的脚本中使用:
document.getElementById("submitPost").addEventListener("click", writeNewPost);
关于javascript - 使用 Javascript 将数据添加到 Firebase 的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718995/