[FireBase] FireBase基本語法
一、如果要使用 firebase 則需先在 html 裡的 <head> 加入
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> <script src="https://cdn.firebase.com/js/client/2.1.0/firebase.js"></script> </head> <body> </body> </html>
二、Creating a Firebase Reference
此語法可以參考到指定的資料層
var rootRef = new Firebase('https://docs-examples.firebaseio.com/web/data');
又如
var rootRef = new Firebase("https://docs-examples.firebaseio.com/web/data/users/mchen/name");
相等於
var rootRef = new Firebase('https://docs-examples.firebaseio.com/web/data'); rootRef.child('users/mchen/name');
三、set()
<!doctype html> <html> <head> <script src='https://cdn.firebase.com/js/client/2.0.4/firebase.js'></script> <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> <link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'> </head> <body> <script> var ref = new Firebase("https://blazing-torch-9471.firebaseio.com/"); var usersRef = ref.child("users"); usersRef.set({ alanisawesome: { date_of_birth: "June 23, 1912", full_name: "Alan Turing" }, gracehop: { date_of_birth: "December 9, 1906", full_name: "Grace Hopper" } }); </script> </body> </html>
相等於
<!doctype html> <html> <head> <script src='https://cdn.firebase.com/js/client/2.0.4/firebase.js'></script> <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> <link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'> </head> <body> <script> var ref = new Firebase("https://blazing-torch-9471.firebaseio.com/"); var usersRef = ref.child("users"); usersRef.child("alanisawesome").set({ date_of_birth: "June 23, 1912", full_name: "Alan Turing" }); usersRef.child("gracehop").set({ date_of_birth: "December 9, 1906", full_name: "Grace Hopper" }); </script> </body> </html>
set() 功能可以創立新值與覆寫值
四、update()
<!doctype html> <html> <head> <script src='https://cdn.firebase.com/js/client/2.0.4/firebase.js'></script> <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> <link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'> </head> <body> <script> var ref = new Firebase("https://blazing-torch-9471.firebaseio.com/"); var usersRef = ref.child("users"); //usersRef.child("alanisawesome").set({ // date_of_birth: "June 23, 1912", // full_name: "Alan Turing" //}); //usersRef.child("gracehop").set({ // date_of_birth: "December 9, 1906", // full_name: "Grace Hopper" //}); var hopperRef = usersRef.child("gracehop"); hopperRef.update({ "nickname": "Amazing Grace22", "full_name": "Grace Hopper22" }); </script> </body> </html>
update() 功能可以複寫值與創立值
set() 與 update() 的不同為 set() 會刪除底下所有節點然後再新增,
而 update() 不會刪除底下節點只會對值做修改,
如果沒有找到 key 時,則會新創一個 value。