所以我最近一直在搞乱Firebase,我遇到了一个需要帮助修复的问题。所以我正在尝试将数据从用户输入发送到Firebase,并且该数据显示在指定的div中,但数据未显示在我的Firebase或该div中...
这是我的HTML代码:
<form>
<input name="name" class="form-control" type="name" placeholder="Title" id="titleInput" />
<br/>
<textarea id="postInput" name="content" data-provide="markdown" rows="10"></textarea>
<hr/>
<button type="submit" class="btn" onclick="submitPost()">Submit</button>
</form>
我的JQuery代码(已编辑):
function submitPost() {
var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
var name = $('#titleInput').val();
var text = $('#postInput').val();
myDataRef.push({name: name, text: text});
$('#postInput').val('');
myDataRef.on('child_added', function(snapshot) {
var post = snapshot.val();
displayUserPost(post.name, post.text);
})
function displayUserPost(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#PostsDiv'));
$('#PostsDiv')[0].scrollTop = $('#PostsDiv')[0].scrollHeight;
}
};
答案 0 :(得分:5)
您正在处理异步数据流,因此您应该监听submitPost函数之外的数据。
var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
myDataRef.on('child_added', function(snapshot) {
var post = snapshot.val();
displayUserPost(post.name, post.text);
});
function submitPost(e) {
var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
var name = $('#titleInput').val();
var text = $('#postInput').val();
myDataRef.push({name: name, text: text});
$('#postInput').val('');
e.preventDefault();
}
function displayUserPost(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#PostsDiv'));
$('#PostsDiv')[0].scrollTop = $('#PostsDiv')[0].scrollHeight;
}