我正在创建一个简单的图书讨论论坛页面作为我的期末作业。我只使用HTML, Javascript和CSS。我对后端有点陌生,刚刚在Google Firebase中设置了一个云数据库。我正在遵循本教程:https://www.youtube.com/watch?v=uVz47tr7vv0并尝试将输入表单连接到数据库。然而,我认为在教程中使用的方法是在Firebase版本8.2.1,而我使用版本9.14.0。参见下面的代码:
HTML:
<div class="form_card">
<form id="submit_form">
<div class="inputBox">
<input type="text" id="title" required="required" autocomplete="off">
<span>Title</span>
</div>
<div class="inputBox">
<input type="text" id="review" required="required" autocomplete="off">
<span>Review</span>
<button type="submit" id="post_btn"><p>POST</p></button>
</div>
</form>
</div>
<script src="form.js" type="module"></script>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyB7ZiJKzHTsgJ3sv8QsOHPLnWCqqnGSSJ0",
authDomain: "litary-project.firebaseapp.com",
projectId: "litary-project",
storageBucket: "litary-project.appspot.com",
messagingSenderId: "147018135042",
appId: "1:147018135042:web:eb4d3d5e9dcb79d89bd91b"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = firebase.firestore(); //I GET ERROR HERE
</script>
Javascript:
//Code
var titleVal = document.getElementById('title');
var reviewVal = document.getElementById('review');
const btn = document.getElementById('post_btn');
btn.addEventListener('click', function handleClick(e) { //Listen to click
e.preventDefault();
const inputs = document.querySelectorAll('#title, #review');
console.log(titleVal.value);
console.log(reviewVal.value);
inputs.forEach(input =>{
input.value = '';
});
});
我已经将firebase初始化为我的HTML代码,如firebase设置中所说,但一旦我尝试调用firebase,(例如firebase.firestore();
)我在边缘检查器中得到此错误:Uncaught ReferenceError: firebase is not defined.
提前感谢!
在脚本之前导入firebase。如果您的脚本是先导入的,它无法知道firebase是什么,因为它在导入firebase之前就运行了您的代码。