Demo: https://github.com/hpcslag/firebase_api
基本上用一段簡單函數就能取得Firebase JSON資料:
var url = "https://popping-torch-7013.firebaseio.com/"; var firebaseRef = new Firebase(url); //firebaseRef.set({name:"MacTaylor",friends:["Mac","Eric","Java"]}); //firebaseRef.push({title:"OK Guys"}); firebaseRef.on('child_added',function(snapshot){ console.log(snapshot.val()); }); })();set 這個東西是單次對資料庫做設定,若要多個存取資料要用 push, 就像array push 這樣
然後透過 on 這個函數可以取得Object資料,而且是即時更新的,所以不需要手動做ajax或是刷新頁面
function subs() { var url = "https://popping-torch-7013.firebaseio.com/"; var firebaseRef = new Firebase(url); var name = $("#names").val(); var tag = $("#tags").val(); var title = $("#titles").val(); var post = $("#posts").val(); if(name.indexOf("@") != -1 && name.length > 1 && tag.length > 1 && title.length > 1 && post.length > 10){ var dats = new Date(); firebaseRef.push({title:title.toString(),name:name.toString(),tag:tag.toString(),post:post,date:dats.toString()}); $("#names").val(null); $("#tags").val(null); $("#titles").val(null); $("#posts").val(null); }else{ alert("Bad Enter!"); } }i = 1; (function() { var url = "https://popping-torch-7013.firebaseio.com/"; var firebaseRef = new Firebase(url); firebaseRef.on('child_added', function(snapshot) { var str = snapshot.val().name; var name = /[A-Za-z0-9]+n*/.exec(str); var website = /@([.0-9a-z_-]+)/gi.exec(str); var post = snapshot.val().post; if (post.indexOf("code: ") != -1) { post = post.replace("code: ", '<pre><code class="javascript hljs">'); post = post.replace(" /code", '</code></pre>'); } /* var ind = document.createElement('div'); ind.sp1.className = "post-preview"; var ac = document.getElementById("inside").appendChild(ind).innerHTML = '<a href="#"><h2 class="post-title">' + snapshot.val().title + '</h2><h3 class="post-subtitle"># ' + snapshot.val().tag + '</h3></a><p>' + post + '</p><p class="post-meta">Posted by ' + '<a href="' + 'http://' + website[1] + '" target="_blank">' + name + '</a>' + ' ' + snapshot.val().date + '<hr>'; */ var sp1 = document.createElement("div"); sp1.className = "post-preview"; sp1.innerHTML = '<a href="#"><h2 class="post-title">' + snapshot.val().title + '</h2><h3 class="post-subtitle"># ' + snapshot.val().tag + '</h3></a><p>' + post + '</p><p class="post-meta">Posted by ' + '<a href="' + 'http://' + website[1] + '" target="_blank">' + name + '</a>' + ' ' + snapshot.val().date + '<hr>'; var sp2 = document.getElementsByClassName("post-preview")[0]; var parentDiv = sp2.parentNode; parentDiv.insertBefore(sp1, sp2); }); })();
沒有留言:
張貼留言