在本章中,我们将向演示如何将数据保存到Firebase。
set
方法将写入或替换指定路径上的数据。 让我们创建一个引用players
收集和设置两个运动员数据信息。
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8" /> <title>FireBase Example</title> <script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "AIzaSyAOSPYpgn7T_bKa6VbCaSeQlsw-3p3zqDs", authDomain: "zyiz-firebase.firebaseapp.com", databaseURL: "https://zyiz-firebase.firebaseio.com/", projectId: "zyiz-firebase", storageBucket: "zyiz-firebase.appspot.com", messagingSenderId: "334522625008" }; firebase.initializeApp(config); var playersRef = firebase.database().ref().child('players'); // console.log(playersRef); playersRef.set ({ John: { number: 1, age: 30 }, Amanda: { number: 2, age: 20 } }); </script> </head> <body>
执行上面示例代码,得到以下结果 -
我们可以用类似的方式更新Firebase数据。 注意我们如何使用players/john
路径。
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8" /> <title>FireBase Example</title> <script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "AIzaSyAOSPYpgn7T_bKa6VbCaSeQlsw-3p3zqDs", authDomain: "zyiz-firebase.firebaseapp.com", databaseURL: "https://zyiz-firebase.firebaseio.com/", projectId: "zyiz-firebase", storageBucket: "zyiz-firebase.appspot.com", messagingSenderId: "334522625008" }; firebase.initializeApp(config); var johnRef = firebase.database().ref().child('players/John'); // console.log(playersRef); johnRef.update ({ "number": 1010 }); </script> </head> <body>
执行上面示例代码,得到以下结果 -