/**
* 表单处理与验证模块 - 集中管理所有表单相关逻辑
*/
const FormHandler = {
/**
* 通用表单提交处理函数
* @param {string} formId - 表单元素的ID
* @param {string} url - 提交表单的目标URL
* @param {function} successCallback - 成功回调函数
* @param {function} errorCallback - 失败回调函数
*/
handleFormSubmit(formId, url, successCallback, errorCallback) {
const form = document.getElementById(formId);
if (!form) {
console.error(`未找到表单元素: ${formId}`);
return;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
// 获取提交按钮并显示加载状态
const submitButton = form.querySelector('button[type="submit"]');
const originalText = submitButton?.innerHTML || '提交';
if (submitButton) {
submitButton.disabled = true;
submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>处理中...';
}
// 表单验证
let isValid = true;
const inputs = form.querySelectorAll('input[required]');
inputs.forEach(input => {
const errorElement = document.getElementById(`${input.id}Error`);
if (errorElement) {
errorElement.classList.add('hidden');
}
// 检查必填字段是否为空
if (!input.value.trim()) {
isValid = false;
if (errorElement) {
errorElement.textContent = `请输入${input.placeholder}`;
errorElement.classList.remove('hidden');
}
}
});
// 如果验证失败,恢复按钮状态并返回
if (!isValid) {
if (submitButton) {
submitButton.disabled = false;
submitButton.innerHTML = originalText;
}
return;
}
// 构建表单数据并发送请求
const formData = new FormData(form);
fetch(url, {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('服务器响应错误');
}
return response.json();
})
.then(data => {
if (data.success) {
// 邮箱验证成功后的特殊处理
if (formId === 'verify_email' && data.redirect_url) {
this.showNotification('success', data.message);
setTimeout(() => {
window.location.href = data.redirect_url;
}, 2000);
} else {
// 执行成功回调
if (typeof successCallback === 'function') {
successCallback(data);
}
}
} else {
// 执行失败回调
if (typeof errorCallback === 'function') {
errorCallback(data);
} else {
this.showNotification('error', data.message || '操作失败,请重试');
}
}
})
.catch(error => {
console.error('请求出错:', error);
this.showNotification('error', '网络错误,请稍后重试');
})
.finally(() => {
// 恢复按钮状态
if (submitButton) {
submitButton.disabled = false;
submitButton.innerHTML = originalText;
}
});
});
},
/**
* 处理登录表单提交
*/
handleLoginForm() {
this.handleFormSubmit('loginForm', '{{ url_for('login') }}',
// 登录成功回调函数
(data) => {
this.showNotification('success', data.message);
setTimeout(() => {
window.location.href = '{{ url_for('index') }}';
}, 1500);
},
// 登录失败回调函数
(data) => {
const messageElement = document.getElementById('loginMessage');
if (messageElement) {
messageElement.textContent = data.message;
messageElement.classList.remove('hidden', 'success-message');
messageElement.classList.add('error-message');
} else {
this.showNotification('error', data.message);
}
}
);
},
/**
* 处理注册表单提交
*/
handleRegisterForm() {
this.handleFormSubmit('registerForm', '{{ url_for('register') }}',
(data) => {
this.showNotification('success', data.message);
},
(data) => {
const messageElement = document.getElementById('registerMessage');
if (messageElement) {
messageElement.textContent = data.message;
messageElement.classList.remove('hidden', 'success-message');
messageElement.classList.add('error-message');
} else {
this.showNotification('error', data.message);
}
}
);
},
/**
* 处理忘记密码表单提交
*/
handleForgotPasswordForm() {
this.handleFormSubmit('forgotPasswordForm', '{{ url_for('forgot_password') }}',
(data) => {
this.showNotification('success', data.message);
},
(data) => {
const messageElement = document.getElementById('forgotPasswordMessage');
if (messageElement) {
messageElement.textContent = data.message;
messageElement.classList.remove('hidden', 'success-message');
messageElement.classList.add('error-message');
} else {
this.showNotification('error', data.message);
}
}
);
},
/**
* 处理重置密码表单提交
*/
handleResetPasswordForm() {
this.handleFormSubmit('resetPasswordForm', '',
(data) => {
this.showNotification('success', data.message);
setTimeout(() => {
window.location.href = '{{ url_for('login') }}';
}, 2000);
},
(data) => {
const messageElement = document.getElementById('resetPasswordMessage');
if (messageElement) {
messageElement.textContent = data.message;
messageElement.classList.remove('hidden', 'success-message');
messageElement.classList.add('error-message');
} else {
this.showNotification('error', data.message);
}
}
);
},
/**
* 检查邮箱验证结果
*/
checkVerificationResult() {
const urlParams = new URLSearchParams(window.location.search);
const success = urlParams.get('success');
const message = decodeURIComponent(urlParams.get('message') || '');
if (success && message) {
const type = success === 'true' ? 'success' : 'error';
this.showNotification(type, message);
history.replaceState({}, document.title, window.location.pathname);
}
},
/**
* 处理重置密码链接
*/
handleResetPasswordLink() {
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
if (token) {
document.getElementById('resetToken').value = token;
this.openModal('reset-password');
}
},
/**
* 检查重置密码令牌
*/
checkResetToken() {
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
if (token) {
document.getElementById('resetToken').value = token;
}
},
/**
* 打开模态框
*/
openModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.classList.remove('hidden');
modal.classList.add('flex');
// 假设存在背景遮罩
const backdrop = modal.querySelector('.backdrop');
if (backdrop) {
backdrop.classList.remove('hidden');
}
}
},
/**
* 显示通知(若notification.js未加载的备用方案)
*/
showNotification(type, message) {
if (window.showNotification) {
window.showNotification(type, message); // 优先使用外部通知函数
} else {
console.log(`[通知] ${type}: ${message}`); // 备用日志输出
}
},
/**
* 处理搜索表单提交
*/
handleSearchFormSubmit() {
const searchForm = document.getElementById('searchForm');
if (searchForm) {
searchForm.addEventListener('submit', (e) => {
e.preventDefault();
const keyword = document.querySelector('input[name="keyword"]').value;
window.location.href = `{{ url_for('search_result') }}?keyword=${encodeURIComponent(keyword)}`;
});
}
},
/**
* 初始化所有功能
*/
init() {
this.checkResetToken();
this.checkVerificationResult();
this.handleResetPasswordLink();
// 初始化表单处理
this.handleLoginForm();
this.handleRegisterForm();
this.handleForgotPasswordForm();
this.handleResetPasswordForm();
// 处理搜索表单
this.handleSearchFormSubmit();
}
};
// 模块化导出 - 兼容Node.js和浏览器环境
if (typeof module !== 'undefined' && module.exports) {
module.exports = FormHandler;
} else {
window.FormHandler = FormHandler; // 浏览器环境暴露为全局对象
}
console.log('FormHandler 模块已加载');
console.log('FormHandler 对象:', FormHandler); 帮我看看哪里少括号了
最新发布