我正在嘗試在網站上為我在學校做的一個專案創建一個聯系我們頁面。當我單擊提交按鈕時,我想將記錄插入 firebase并檢查電子郵件地址的有效性。我可以讓他們兩個單獨作業,但不能一起作業。
我已經嘗試將它們分成 2 個功能,但我仍然無法讓它作業。我正在使用 onclick="insertRecord()"。當我使用下面的代碼執行此操作時,驗證代碼有效,但用戶條目不會被推送到 Firebase。當我取出驗證部分時,它發送條目沒有問題!我非常感謝任何建議。謝謝你。
firebase.initializeApp(firebaseConfig);
function insertRecord(){
var name=document.getElementById("nameIn").value;
var pn=document.getElementById("phoneNumIn").value;
var email=document.getElementById("Email").value;
var date=document.getElementById("Date").value;
var choice=document.getElementById("contactby").value;
if (email.includes("@")&& email.includes(".")) {
alert("Your details have been submitted");
location.href = "contactus.html"
}
else {
alert("Invalid Email Address. Please try again");
location.reload();
}
var myDB=firebase.database().ref();
var addRecord=myDB.child('Contacts').push();
record = {
"nameIn":name,
"phoneNumIn":pn,
"Email":email,
"Date":date,
"contactby":choice
}
addRecord.set(record);
}
uj5u.com熱心網友回復:
問題是寫入資料庫是異步操作,并且您 location.href = "contactus.html"正在導致當前頁面在寫入操作完成之前卸載。
您需要同步這兩個操作:等待寫入完成,然后導航到新頁面。
function insertRecord(){
var name=document.getElementById("nameIn").value;
var pn=document.getElementById("phoneNumIn").value;
var email=document.getElementById("Email").value;
var date=document.getElementById("Date").value;
var choice=document.getElementById("contactby").value;
if (email.includes("@")&& email.includes(".")) {
var myDB=firebase.database().ref();
var addRecord=myDB.child('Contacts').push();
record = {
"nameIn":name,
"phoneNumIn":pn,
"Email":email,
"Date":date,
"contactby":choice
}
addRecord.set(record).then(() => { // ?? wait for write to complete
alert("Your details have been submitted");
location.href = "contactus.html"; // ?? then move to the new page
})
}
else {
alert("Invalid Email Address. Please try again");
location.reload();
}
}
uj5u.com熱心網友回復:
從“firebase/database”匯入 { getDatabase , update,ref }; 常量 db = getDatabase();
函式插入記錄(){
var name=document.getElementById("nameIn").value;
var pn=document.getElementById("phoneNumIn").value;
var email=document.getElementById("Email").value;
var date=document.getElementById("Date").value;
var choice=document.getElementById("contactby").value;
if (email.includes("@")&& email.includes(".")) {
record = {
"nameIn":name,
"phoneNumIn":pn,
"Email":email,
"Date":date,
"contactby":choice
}
const updates = {};
updates[`/Contacts/${name}`] = record;
return firebase.database().ref().update(updates);
alert("Your details have been submitted");
location.href = "contactus.html"
}
else {
alert("Invalid Email Address. Please try again");
location.reload();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/420636.html
標籤:
