document.addEventListener('DOMContentLoaded', function() { const switchRoleButton = document.getElementById('switch-role'); const loginForm = document.getElementById('login-form'); const usernameLabel = document.getElementById('username-label'); const usernameInput = document.getElementById('username'); const passwordInput = document.getElementById('password'); const registerLinkHref = document.getElementById('register-link-href'); let isTeacherLogin = false; // 切换角色按钮点击事件 switchRoleButton.addEventListener('click', function() { isTeacherLogin = !isTeacherLogin; // 切换状态 toggleButtonColor(isTeacherLogin); toggleLoginFields(isTeacherLogin); }); // 根据角色切换按钮背景色 function toggleButtonColor(isTeacher) { if (isTeacher) { loginForm.classList.add('teacher-login'); } else { loginForm.classList.remove('teacher-login'); } } // 切换显示不同的表单字段 function toggleLoginFields(isTeacher) { if (isTeacher) { // 显示教师登录字段 usernameLabel.textContent = '教师用户名'; switchRoleButton.textContent = '切换到学生登录'; // 更新按钮文本 registerLinkHref.href = '/register_teacher'; registerLinkHref.textContent = '注册新教师账号'; } else { // 显示学生登录字段 usernameLabel.textContent = '学生用户名'; switchRoleButton.textContent = '切换到教师登录'; // 更新按钮文本 registerLinkHref.href = '/register'; registerLinkHref.textContent = '注册新学生账号'; } } // 处理登录提交 loginForm.addEventListener('submit', function(event) { event.preventDefault(); // 防止默认提交 const username = usernameInput.value.trim(); const password = passwordInput.value.trim(); if (!username || !password) { alert('请填写所有必需的字段'); return; } // 登录请求的 URL 依据角色不同而不同 const loginUrl = isTeacherLogin ? '/login_teacher_post' : '/login_post'; const data = isTeacherLogin ? { username, password } : { username, password }; // 发送登录请求 fetch(loginUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) // 将数据发送到后端 }) .then(response => response.json()) .then(data => { if (data.success) { // 登录成功,跳转到主页 if (isTeacherLogin) { window.location.href = '/teacherboard'; } else { window.location.href = '/dashboard'; } } else { // 登录失败,提示错误信息 alert('登录失败: ' + data.message); } }) .catch(error => { console.error('Error:', error); alert('登录请求失败,请稍后重试'); }); }); });