2016-04-12 72 views
1

我想在firebase中存儲/推送輸入數據。使用Ajax保存輸入數據

表HTML

<form> 
<input name="name" type="name" placeholder="Title" id="titleInput" /> 
<button type="submit" class="btn" onclick="submitPost()">Submit</button> 
</form> 

推輸入數據火力

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 = $('#titleInput').val(); 
    myDataRef.push({name: name}); 
} 

上面的代碼工作在這個jsfiddle。在我的情況下,我不能將https://cdn.firebase.com/v0/firebase.js放在網站標題中,所以我想通過Ajax嘗試。

HTML表格與jQuery的

$('header').prepend ('<form><input name="name" type="name" id="titleInput"/>  
<button type="submit" onclick="submitPost()">Submit</button></form>'); 

我不是很熟悉,Ajax和下面的代碼轉化不工作。幫幫我?

$.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(); 
    displayUserPost(post.name); 
}); 
} 
}); 

$.ajax({ 
    url: 'https://cdn.firebase.com/v0/firebase.js', 
    dataType: 'script', 
    cache: true, 
    success: function submitPost(e) { 
    var myDataRef = new Firebase('https://eloquatest.firebaseio.com/'); 
    var name = $('#titleInput').val(); 
    myDataRef.push({name: name}); 
    $('#postInput').val(''); 
    e.preventDefault(); 
} 
}); 

回答

1

這個想法是通過javascript爲我們的DOM添加第三個腳本。 添加onload函數來處理第三個腳本加載和做你的東西。

你可以將這個腳本添加到你的js文件上,準備好文檔並不是一個壞主意。

window.firebaseInit = function(){ 
    var myDataRef = new Firebase('https://eloquatest.firebaseio.com/'); 
    ...... 
    <Do whatever you want here!> 
}; 

(function(d, s, id){ 
    var js, fjs = d.getElementsByTagName(s)[0]; 
    if (d.getElementById(id)) {return;} 
    js = d.createElement(s); js.id = id; 
    js.src = "//cdn.firebase.com/v0/firebase.js"; 
    js.onload = window.firebaseInit; 
    fjs.parentNode.insertBefore(js, fjs); 
}(document, 'script', 'id-firebase')); 

這個腳本,我從Facebook學習。您可以使用jQuery.getScript並將您的init FireBase函數放在成功參數上,文檔位於:https://api.jquery.com/jquery.getscript/