我试图链接我的html联系人表单与firebase,但我面临一个错误:
我在我的html文件中定义了我的CDN,但在main.js行是我面对这个错误的地方。我成功地在我的项目中安装了firebase,但是我仍然面临同样的问题未捕获的引用错误:firebase is not defined
var emailRef = firebase.database().ref('emails');
在我的main.js代码中
var emailRef = firebase.database().ref('emails');
// Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm);
// Submit form
function submitForm(e){
e.preventDefault();
//Get values
var FullName = getInputval('FullName');
var Email =getInputval('Email');
// save message
saveMessage(FullName,Email);
// Show alert
document.querySelector('.alert').style.display = 'block';
// Hide alert after 3 seconds
setTimeout(function(){
document.querySelector('.alert').style.display = 'none';
},3000);
// Clear form
document.getElementById('contactForm').reset();
}
// Function to get form values
function getInputval(id){
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(Fullname, Email,){
var newEmailRef = emailRef.push();
newEmailRef.set({
Fullname: Fullname,
Email:Email
});
}
在我的index。html文件中这里是我的CDN格式
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-analytics.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
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "xxxxx",
authDomain: "xxxxx",
projectId: "xxxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx",
appId: "xxxxx",
measurementId: "xxxxx"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
<script src="main.js"></script>
第二个代码段是在这里以ES模块格式导入Firebase的第9版:
<script type="module">
但是在第一个代码片段中,您尝试使用Firebase的旧语法与firebase.database()
。
这不起作用:您将不得不使用新的导入格式和语法,或者使用旧的命名空间语法。
相当于v8的代码:
var emailRef = firebase.database().ref('emails');
在v9模块语法中应该是:
import { getDatabase, ref } from "firebase/database";
// Get a reference to the database service
const database = getDatabase(app);
var emailRef = ref(database, 'emails');
v8中的代码:
function saveMessage(Fullname, Email,){
var newEmailRef = emailRef.push();
newEmailRef.set({
Fullname: Fullname,
Email:Email
});
}
在v9中看起来像这样:
import { getDatabase, ref, push, set } from "firebase/database";
function saveMessage(Fullname, Email,){
var newEmailRef = push(emailRef);
set(newEmailRef, {
Fullname: Fullname,
Email:Email
});
}
当您使用新旧语法的组合时,我建议您随身携带升级指南。