0
私が行っているページは、ユーザーが持つ質問を保存します。 つまり、ボディが読み込まれるとすべての質問が表示されます。ユーザーが新しい質問を投稿すると、データはfirebaseに保存され、本体は再度読み込まれ、以前に投稿された他の質問(データベース内にある)と共に投稿された新しい質問が表示されます。ボディオンロードがデータベースにデータを保存する機能で衝突する
<script>
function saveToDB() {
// Initialize Firebase
var config = {
apiKey: "AIzaSyDH1bPI9AZj4gFGyCYVNNWA7xvr9sU9Qvw",
authDomain: "show-off-your-talent-b9923.firebaseapp.com",
databaseURL: "https://show-off-your-talent-b9923.firebaseio.com",
storageBucket: "show-off-your-talent-b9923.appspot.com",
messagingSenderId: "1005390925584"
};
if(firebase.apps.length===0){
firebase.initializeApp(config);
var dbRef = firebase.database().ref().child('qns');
var question = document.getElementById("myTextarea").value;
var postData = {
qnsask : question
};
dbRef.push(postData);
document.getElementById("response").innerHTML = "POSTED!";
dbRef.once('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
var childData = childSnapshot.val();
document.getElementById("questions").innerHTML = document.getElementById("questions").innerHTML + "</br>" + childData.qnsask;
});
});
}
}
function Retrieve() {
// Initialize Firebase
var config = {
apiKey: "somekey",
authDomain: "somekey.firebaseapp.com",
databaseURL: "https://somekey.firebaseio.com",
storageBucket: "somekey.appspot.com",
messagingSenderId: "somekey"
};
if(firebase.apps.length===0){
firebase.initializeApp(config);
}
var dbRef = firebase.database().ref().child('qns');
dbRef.once('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
var childData = childSnapshot.val();
document.getElementById("questions").innerHTML = document.getElementById("questions").innerHTML + "</br>" + childData.qnsask;
});
});
}
</script>
</head>
<body onload="Retrieve()">
<div id="forum">
<form action="#" onsubmit="saveToDB(); return false">
<p class="qns">
<label for="qn">Your question:</label>
<textarea rows="5" cols="100" id="myTextarea"></textarea>
</p>
<input type="reset" class = "button" value="Cancel">
<input type="submit" value="Post" class = "button button1">
<p id ="response"></p>
</div>
<div id="questions">
</div>
</body>
これで、本体にonload関数を追加する前に、saveToDB()関数がうまく動作するようになりました。
Retrieveはコンソールでエラーをスローしていますか? –