读取用于全球聊天室和聊天室的Firebase实时数据库

时间:2020-03-21 07:34:30

标签: jquery firebase-realtime-database

我有一个适用于全球聊天室的Firebase实时数据库,其默认userSession ='xxxxx'。我想添加具有用户定义的房间编号(称为userSession)的子聊天室。一个示例房间是“ 12345”。我尝试为第二个孩子使用变量,并且该变量适用于全局聊天,但是在用户更改房间时不会更新。我正在尝试让程序创建数据库“会话”的快照,然后将每个session.key的值与userSession的值进行比较。如果匹配,则程序应从该sessions.key获取用户和消息值。

聊天HTML:

<div class="chat">
  <div class="chathead toggle" data-aquired="chatbody">CRACKED <i class="fas fa-comments"></i></div>
  <div id="chatbody" class="hide">
    <div id="chatmsgs"><p>User: Welcome to the Global Chat!</p></div>
    <div id="chattxt">
    <input type='text' id='chatmsg' maxlength="530" placeholder='Type a message...'>
    </div>
    <div >&nbsp; </div>
  </div>
</div>

全局聊天JQuery:

firebase.database().ref().child("sessions").child(userSession).on('value', function (snapshot) {
var user = snapshot.val().name;
var mess = snapshot.val().message;
var chat = "<p>"+user+": "+mess+"</p>";
$('#chatmsgs').append(chat);
}, function (error) {
if (error) {
  console.log("The read failed: " + error.code);
}})

从Firebase导出JSON文件:

"sessions" : {
"12345" : {
  "message" : "test",
  "name" : "User"
},
"xxxxx" : {
  "message" : "Let me know how you like the updates!",
  "name" : "user"
}
}

尝试:

firebase.database().ref().child("sessions").on('value', function (snapshot) {
snapshot.forEach(function (data) {
  if (userSession == data.key) { // LINE 767 mentioned in DataSnapshot.forEach failed: 2 arguments vs 1.
    var user = data.name;
    var mess = data.message;
    var chat = "<p>"+user+": "+mess+"</p>";
    $('#chatmsgs').append(chat);
  }
}, function (error) {
  if (error) {
    console.log("The session read failed: " + error.code);
  }
})
}, function (error) {
if (error) {
  console.log("The sessions read failed: " + error.code);
}
})

0 个答案:

没有答案