编辑:我想将表单中的输入数据保存到Firebase数据库
带有id="field0"
的输入和带有onClick"submitPost()"
<form>
<input id="field0" name="ePost" type="text" value="">
<button type="submit" class="btn" onclick="submitPost()">Submit</button>
</form>
无法将firebase.js放入头部。所以就这样解决了。如果我将这些代码片段逐个添加到控制台中,它似乎可以正常工作。但是当我同时在控制台中加载它们时会出错。
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://cdn.firebase.com/v0/firebase.js";
document.head.appendChild(script);
var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
myDataRef.on('child_added', function(snapshot) {
var post = snapshot.val();
});
function submitPost(e) {
var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
var name = $('#field0').val();
myDataRef.push({name: name});
$('#field0').val('');
}
以上是上述示例:https://jsfiddle.net/hbaecklund/7mnns4dk/5/
我是否需要执行脚本的异步加载才能工作?但下面不起作用?
$.ajax({
url: 'https://cdn.firebase.com/v0/firebase.js',
dataType: 'script',
cache: true,
success: function() {
var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
myDataRef.on('child_added', function(snapshot) {
var post = snapshot.val();
});
function submitPost(e) {
var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
var name = $('#field0').val();
myDataRef.push({name: name});
$('#field0').val('');
};
}
});
答案 0 :(得分:1)
尝试使用脚本标记的加载事件:https://jsfiddle.net/7mnns4dk/6/
基本上只是使用:
script.load = function() {
// enter code that needs the script to be loaded here
}
当你编写它时,它也适用于jQuery,只需移动submitPost函数,以便按钮可以访问它:https://jsfiddle.net/7mnns4dk/7/