简体   繁体   中英

How can I display the snapshot data in HTML?

I'm trying to display the snapshot data from the database to the html page, but it seems to display an '[object Object]'instead of the gmail. I'm new to code so please be patient. here is the code:

firebase.database().ref('gmails/').get().then((snapshot) => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
    var content = '';
 // give each message a unique ID
         content += "<li>";
            content +=  snapshot.val();
         content += "</li>";
 
         document.getElementById("gmails").innerHTML += content;
  } else {
    console.log("No data available");
  }
}).catch((error) => {
  console.error(error);
});

THE HTML:

<ul id="gmails">
    
</ul>

enter image description here

In the image you can see the object instead of the value

It sounds like you have a javascript Object which contains data that you want to render as text on your page. When you see [object Object] it's a sign that you're trying to render something as text that your code doesn't know how to turn into text, in this case your snapshot object.

There are a few simple things you can try / questions you can answer for yourself:

  • What is the "shape" of your snapshot object? Do you know the names of variables it contains? Are they supposed to be strings? Is it wrapping HTML of some kind? If so, you'll probably want to render either specific strings inside the object or one big string contained inside. If it's HTML I believe you can just insert it the way you already are.

If you don't know the structure of the contents of snapshot , there are some easy ways to figure it out:

  • If you know how to use the Chrome debugger ("source" tab of the dev tools, ctrl-P or command-P to search for your relevant file, and click on the line number to add a breakpoint), put a breakpoint on console.log(snapshot.val()); and inspect the value of snapshot . You can hover over it and click into its child-objects, and determine their names and structure for accessing and finding the strings you want to display

  • If you want a simple solution without tools, you can change console.log(snapshot.val()); ...to: console.log(JSON.stringify(snapshot)); ...and see how your data is structured as JSON. That will just drop the whole object into your console, which I assume is just displaying `[object Object] as-is.

Once you have that figured out, you should be able to access the right children of snapshot that contain the text you're trying to render.

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