为什么读取[object Object]?

时间:2019-03-31 20:12:00

标签: javascript jquery html firebase firebase-realtime-database

我正在尝试从Firebase中读取内容,但是我继续获取此[object Object]。我不知道我是在读错还是数据库有问题。我也尝试过使用jQuery,但无法正常工作。我可能错过的事情确实很简单。

//var transcript_title = null;
//var transcript = null;
//This is to intialize everything and auth. with the firebase server
var config = {
    apiKey: "AIzaSyB9p1VvVfhnbrcDwUKUuSqw9aQsqnDi4nQ",
    authDomain: "html5project-870df.firebaseapp.com",
    databaseURL: "https://html5project-870df.firebaseio.com",
    projectId: "html5project-870df",
    storageBucket: "html5project-870df.appspot.com",
    messagingSenderId: "54935462861"
};

//firebase.initializeApp(config);
//checks if it has been init
if (!firebase.apps.length) {
    firebase.initializeApp({});
}

//declare variables
var database = firebase.database();
//tells where the items are going to be 
var Rootref = database.ref().child("users");
var ref = firebase.database().ref("users");

ref.on("value", function(snapshot) {
    console.log(snapshot.val());
}, function (error) {
    console.log("Error: " + error.code);
});

//var Rootref1 = database.ref().child("users").child("id: 113295907411766134791")/*.child("trans")*/;
//used to retrieve data 
Rootref.on("child_added",snap => { 
    //gets the child of titles stores it as variable
    var transcript_title = snap.child("titles").val();
    //var transcript_title = (snap.val() && snap.val().titles);
    //gets the actual title and stores it as a var
    //var transcript = snap.child(transcript_title).val();

    $('#transcrip').val(snap.child('users/id: 107621796826103613669'))
    //jquery - way to add html elemnts with javascript

    $("#read").append('<h4 id = "clicked">'+transcript_title+'</h4>');
    //$("#read").append('<h4 >Test</h4>');

    //when button view was clicked it will show the transcriptiodn
});
{
  "users" : {
    "id: 107621796826103613669" : {
      "hi1" : [ "test" ],
      "hi2" : [ "hi" ],
      "hi23" : [ "hi3" ],
      "hi3" : [ "blaha" ],
      "test" : [ "blahblah" ],
      "test2" : [ "te2" ],
      "titles" : {
        "1" : "hi1",
        "2" : "hi1",
        "184" : "test2",
        "230" : "test",
        "1192012017" : "hi3",
        "2019201220" : "test"
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您正在使用以下内容阅读标题:

var transcript_title = snap.child("titles").val();

哪个翻译成以下JSON:

  "titles" : {
    "1" : "hi1",
    "2" : "hi1",
    "184" : "test2",
    "230" : "test",
    "1192012017" : "hi3",
    "2019201220" : "test"
  }

这是一个对象,因此当您将其设置为HTML时,它将使用[object Object]显示该对象(请注意,不同的浏览器可能对此处理方式有所不同)。要以HTML格式获取完整的JSON作为文本,可以使用JSON.stringify(...)

$("#read").append('<h4 id = "clicked">'+JSON.stringify(transcript_title)+'</h4>');

如果您想显示所有标题,则可以循环显示它们:

snap.child("titles").forEach(function(titleSnap) {
  $("#read").append('<h4 id = "clicked">'+titleSnap.val()+'</h4>');
})