51 lines
1.6 KiB
JavaScript
51 lines
1.6 KiB
JavaScript
// 页面加载时检查是否已登录
|
|
(function() {
|
|
const token = localStorage.getItem('token');
|
|
if (token) {
|
|
window.location.href = '/chat.php';
|
|
}
|
|
})();
|
|
|
|
// 登录表单提交
|
|
document.getElementById('loginForm').addEventListener('submit', async function(e) {
|
|
e.preventDefault();
|
|
const btn = document.getElementById('loginBtn');
|
|
const errorEl = document.getElementById('loginError');
|
|
const username = document.getElementById('username').value.trim();
|
|
const password = document.getElementById('password').value;
|
|
|
|
if (!username || !password) {
|
|
errorEl.textContent = '请输入用户名和密码';
|
|
errorEl.classList.remove('hidden');
|
|
return;
|
|
}
|
|
|
|
btn.disabled = true;
|
|
btn.textContent = '登录中...';
|
|
errorEl.classList.add('hidden');
|
|
|
|
try {
|
|
const response = await fetch('/api/auth/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, password })
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.success) {
|
|
localStorage.setItem('token', data.data.token);
|
|
window.location.href = '/chat.php';
|
|
} else {
|
|
errorEl.textContent = data.message || '登录失败';
|
|
errorEl.classList.remove('hidden');
|
|
}
|
|
} catch (err) {
|
|
errorEl.textContent = '网络错误,请稍后重试';
|
|
errorEl.classList.remove('hidden');
|
|
} finally {
|
|
btn.disabled = false;
|
|
btn.textContent = '登录';
|
|
}
|
|
});
|