在实时数据库中检索特定值 - Firebase

Retrieve specific values in a Realtime Database - Firebase

我的目标是能够通过 javascript 从 firebase 上的实时数据库中检索某些值。我已配置好所有内容并且运行良好,但我不知道如何在单击简单按钮时检索各个字段。

This is an example of the values I would like to be able to take

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
     <button type="submit" id="searchData" class="btn btn-primary">Search data</button>
  </body>
  </html>

  <script type="module">

  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js";
  import { getDatabase, set, ref ,push, child, onValue} from "https://www.gstatic.com/firebasejs/9.6.8/firebase-database.js";

  const firebaseConfig = {
    apiKey: "********************************",
    authDomain: "********************************",
    databaseURL: "********************************",
    projectId: "********************************",
    storageBucket: "****************************",
    messagingSenderId: "******************",
    appId: "********************************"
  };

  const app = initializeApp(firebaseConfig);
  const db = getDatabase(app);


searchData.addEventListener('click',(e) => {

  //
  
});
</script>

你可以尝试使用我经常实现的这个例子,注意我的主文件是用户,然后我的键值作为 id 是 userId 然后我有属性 username 和 useremail。试试这个:

I want to obtain a name:

const dbRef=ref(db, 'users/'+userId);
onValue(dbRef, (snapshot)=>{
  const data=snapshot;
  for(let i in data){
    console.log(snapshot.val().username);
    txtCont.innerHTML=`<p>${snapshot.val().username}</p>`;
  }
  
});