[英]Can't read data from Firebase database with .once() function
我希望能夠在按鈕觸發onclick
事件時從Firebase
數據庫中讀取一條數據。 從文檔開始看,似乎once()
函數是這里的解決方法,因為我不是試圖將數據讀取鏈接到任何特定的Firebase
事件,例如添加一個孩子,而是當有人單擊一個頁面上的按鈕。 這是我調用once()
...
curPoll.once('value', function(curPollSnapshot) {
numElections = curPollSnapshot.val().NumElections;
});
問題是,即使curPoll
設置為數據引用並且numElections
是腳本中的全局變量,我也無法讀取數據。 numElections不斷返回未定義狀態。 實際上,我似乎甚至都無法進入FireBug中的函數,就好像出現語法錯誤一樣。 如果出現語法錯誤,我將無法解決,無論如何,我認為整個腳本根本無法在Firebug中加載。 但是,由於某種原因,我可能無法進入該功能以查看發生了什么。
這是設置curPoll的功能...
function createPoll()
{
var pollName = $('#txtCreatePoll').val();
if (pollName == "" || pollName == null)
{
alert("You must enter a name for your poll!");
return;
}
else
{
pollsRef = new Firebase('https://poll-database.firebaseio.com/Polls');
//TODO add error callback
curPoll = pollsRef.push({Name: pollName, Elections: null, NumElections: 0 });
elections = curPoll.push();
$('div#divCreateElections1').slideDown('slow');
}
}
如您所見, elections
參考作為curPoll
的子項被推入此處。
這是我嘗試從選舉參考中讀取數據的功能。
function addElection()
{
curPoll.once('value', function(curPollSnapshot) {
numElections = curPollSnapshot.val().NumElections;
});
var electionName = $('div#divCreateElections' + (parseInt(numElections)+1) + ' > input#txtCreateElection').val();
var numberToElect = $('div#divCreateElections' + (parseInt(numElections)+1) + ' > input#txtNumElect').val();
if (electionName == "" || electionName == null)
{
alert("You must enter a name for your election!");
return;
}
}
就像我說的那樣,numElections不斷上升。 這是我的Firebase數據庫的基本結構...
Poll-Database > Polls > Poll1
Poll2
...
Polln > Name
> NumElections
> Elections > Election1
> Election2
...
> Electionn
以防萬一,這是我頁面的正文...
<body>
<div id="divCreatePoll">
Enter Name of New Poll:
<input type="text" id="txtCreatePoll" value="" />
<br /><br />
<button id="btnCreatePoll" onclick="createPoll(); return false;">CREATE POLL</button>
<p id="pError"></p>
</div>
<div id="divCreateElections1">
Enter Election Name:
<input type="text" id="txtCreateElection" value="" />
<br /><br />
Enter Number of Candidates to Elect:
<input type="text" id="txtNumElect" value="" />
<br /><br />
<button id="btnCreateElection" onclick="addElection(); return false;">CREATE ELECTION</button>
<br /><br />
<p id="pError"></p>
</div>
</body>
問題是once
是一個異步調用。 因此,它不會立即設置numElections
。 因此,當您使用numElections時,尚未設置它。
您只需要在回調內移動其余代碼。
function addElection() {
curPoll.once('value', function(curPollSnapshot) {
numElections = curPollSnapshot.val().NumElections;
var electionName = $('div#divCreateElections' + (parseInt(numElections)+1) + ' > input#txtCreateElection').val();
var numberToElect = $('div#divCreateElections' + (parseInt(numElections)+1) + ' > input#txtNumElect').val();
if (electionName == "" || electionName == null)
{
alert("You must enter a name for your election!");
return;
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.