如何用JavaScript从Cloud Firestore获取用户名填充至下拉菜单
解决方案
1. 确保注册时用户名存入Firestore
先确认你的myScript.js包含将注册用户信息写入Firestore的逻辑,这样后续才能读取到用户名。示例代码如下:
// myScript.js document.getElementById('signupBtn').addEventListener('click', async () => { const userName = document.getElementById('userName').value; const email = document.getElementById('Email').value; const password = document.getElementById('password').value; try { // 创建Firebase Auth用户 const userCredential = await auth.createUserWithEmailAndPassword(email, password); const user = userCredential.user; // 将用户名写入Firestore的users集合 await db.collection('users').doc(user.uid).set({ userName: userName, email: email }); alert('注册成功'); } catch (error) { console.error(error.message); alert(error.message); } });
2. 编写用户列表页面(含下拉菜单)
创建你提到的第二个HTML页面(命名为user-list.html),引入Firebase SDK并编写逻辑从Firestore拉取用户名填充下拉菜单:
<html> <head> <meta charset="utf-8"> <title>已注册用户</title> </head> <body> <h3>选择用户登录</h3> <select id="userDropdown"> <option value="">请选择用户名</option> </select> <!-- 引入与注册页版本一致的Firebase SDK --> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js"></script> <script> // 复用注册页的Firebase配置 const firebaseConfig = { apiKey: "AIzaSyD2izIZyRC1IKqfc5RaZ-HHx0CmxTYNNws", authDomain: "login-with-firebase-data-ae61f.firebaseapp.com", projectId: "login-with-firebase-data-ae61f", storageBucket: "login-with-firebase-data-ae61f.appspot.com", messagingSenderId: "905524976644", appId: "1:905524976644:web:643932fd262d0b89346951" }; firebase.initializeApp(firebaseConfig); const db = firebase.firestore(); // 页面加载时获取所有用户名并填充下拉菜单 window.addEventListener('load', async () => { const dropdown = document.getElementById('userDropdown'); try { // 查询users集合的所有文档 const querySnapshot = await db.collection('users').get(); querySnapshot.forEach(doc => { const userData = doc.data(); // 创建选项元素并添加到下拉菜单 const option = document.createElement('option'); option.textContent = userData.userName; option.value = userData.userName; // 可替换为用户ID用于后续登录验证 dropdown.appendChild(option); }); } catch (error) { console.error('加载用户列表失败:', error); alert('无法加载用户列表,请稍后重试'); } }); </script> </body> </html>
3. 绑定登录按钮的新窗口打开逻辑
在myScript.js中添加点击事件,让登录按钮打开用户列表页面:
// myScript.js document.getElementById('signinBtn').addEventListener('click', () => { // 打开新窗口展示用户列表页面,可自定义窗口尺寸 window.open('user-list.html', '_blank', 'width=450,height=350'); });
4. 配置Firestore安全规则
前往Firebase控制台的Firestore规则页面,确保允许读取users集合(生产环境建议限制为已登录用户读取,避免公开数据):
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read: if true; // 测试环境可临时开放,生产环境改为request.auth != null allow write: if request.auth != null && request.auth.uid == userId; } } }
内容的提问来源于stack exchange,提问作者RaVi Narayan
相关产品推荐
相关产品推荐

