简体   繁体   中英

How can I display the data from my Firebase Database in my web site?

On Firebase, I am having the following issue; my data being structured as this:

myApp
- myList
    - KKJJXX...1        myString: "String One"
    - KKJJXX...2        myString: "String Two"
    - KKJJXX...3        myString: "String Three"

I want to make some JavaScript (in a web page of mine) to list the values of myString in the DB above. Here is what I came up with after digging the web. It works to a point, but not quite. I can see in the debugging console of my browser that I have got the data I want. I write my concerns more precisely after the script.

<script>
var ref = new Firebase("https://myApp.firebaseio.com/myList/");

ref.on("value", function(snapshot) {
    for (x in snapshot.val()) {
        var xRef = new Firebase("https://myApp.firebaseio.com/myList/"+x+"/");
        xRef.once("value", function(xsnapshot) {
            var name = xsnapshot.child("myString");
            console.log(name);
        });
    }
}, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
});
</script>

In the debugging console I get this line(3 times):

Object { A: Object, Y: Object, g: Object }

And I can see that the A Object contains the information I am looking for (myString). What should I change in the script above to list directly the contents of myString on the console?

When you call child , you're getting a new FirebaseReference -- not a data snapshot. You'd need to .on('value') it to fetch the ref's data, but that would be silly because you already have the data.

Instead, just stash the snapshot's data in a local variable and operate over that.

ref.on("value", function(snapshot) {
    for (x in snapshot.val()) {
        var xRef = new Firebase("https://myApp.firebaseio.com/myList/"+x+"/");
        xRef.once("value", function(xsnapshot) {
            var data = xsnapshot.val();
            var name = data["myString"];
            console.log(name);
        });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM