心理咨询第一阶段系统前端
// static/js/modules/counselor-manager.js
console.log('✅ counselor-manager.js 加载成功');
// 添加加载状态管理函数
if (!window.showLoading) {
window.showLoading = function() {
console.log('显示加载状态');
// 可以在这里添加加载动画
};
}
if (!window.hideLoading) {
window.hideLoading = function() {
console.log('隐藏加载状态');
// 可以在这里移除加载动画
};
}
if (!window.showError) {
window.showError = function(message) {
console.error('显示错误:', message);
alert(message || '操作失败');
};
}
// 加载咨询师列表
async function loadCounselorList() {
try {
window.showLoading();
const response = await fetch('/admin/counselors/list-view');
const html = await response.text();
// 插入HTML
const contentArea = document.getElementById('content-area');
contentArea.innerHTML = html;
console.log('咨询师列表HTML已加载');
// 查找所有脚本并执行
executeScripts(contentArea);
// 全局绑定禁用函数
bindGlobalFunctions();
window.hideLoading();
} catch (error) {
console.error('加载咨询师列表失败:', error);
window.showError('加载失败:' + error.message);
window.hideLoading();
}
}
// 执行脚本的函数
function executeScripts(container) {
const scripts = container.getElementsByTagName('script');
console.log('找到脚本数量:', scripts.length);
for (let script of scripts) {
try {
if (script.textContent.trim()) {
console.log('执行脚本:', script.textContent.substring(0, 50) + '...');
// 创建新脚本元素并执行
const newScript = document.createElement('script');
newScript.textContent = script.textContent;
// 确保函数是全局的
const scriptContent = script.textContent;
if (scriptContent.includes('function handleDisableCounselor')) {
newScript.textContent = 'window.handleDisableCounselor = ' +
scriptContent.match(/function handleDisableCounselor\([^)]*\)\s*{[\s\S]*?}/)[0];
}
document.head.appendChild(newScript);
document.head.removeChild(newScript);
console.log('脚本执行成功');
}
} catch (e) {
console.error('执行脚本失败:', e);
}
}
}
// 绑定全局函数
function bindGlobalFunctions() {
// 如果还没有handleDisableCounselor,创建一个
if (!window.handleDisableCounselor) {
console.log('创建全局handleDisableCounselor函数');
window.handleDisableCounselor = async function(id) {
console.log('handleDisableCounselor被调用,ID:', id);
if (confirm('确定要禁用这个咨询师吗?')) {
try {
const response = await fetch('/admin/counselors/' + id + '/status', {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({status: 'DISABLED'})
});
const data = await response.json();
if (data.success) {
alert('已禁用');
// 刷新页面
if (window.loadCounselorList) {
window.loadCounselorList();
} else if (window.loadPage) {
window.loadPage('counselor-manage');
}
} else {
alert('操作失败: ' + (data.message || '未知错误'));
}
} catch (error) {
console.error('禁用失败:', error);
alert('禁用失败: ' + error.message);
}
}
};
}
}
// 加载添加咨询师表单
async function loadAddCounselor() {
try {
window.showLoading();
const response = await fetch('/admin/counselors/add-view');
const html = await response.text();
document.getElementById('content-area').innerHTML = html;
console.log('添加咨询师表单加载完成');
} catch (error) {
console.error('加载添加咨询师表单失败:', error);
window.showError('加载失败:' + error.message);
}
}
// 加载编辑咨询师表单 - 修复版本
async function loadEditCounselor(id) {
console.log('🎯 加载编辑页面,ID:', id);
try {
window.showLoading();
const response = await fetch(`/admin/counselors/${id}/edit-view`);
const html = await response.text();
// 插入HTML
document.getElementById('content-area').innerHTML = html;
console.log('编辑页面HTML已加载');
// 查找并执行脚本
const scripts = document.getElementById('content-area').getElementsByTagName('script');
console.log('找到脚本数量:', scripts.length);
for (let script of scripts) {
try {
// 执行脚本
eval(script.textContent);
console.log('执行脚本成功');
} catch (e) {
console.error('执行脚本失败:', e);
}
}
// 设置咨询师ID并触发数据加载
window.counselorId = id;
console.log('已设置 window.counselorId =', id);
// 手动触发数据加载
setTimeout(() => {
if (typeof loadCounselorData === 'function') {
console.log('调用 loadCounselorData...');
loadCounselorData(id);
} else {
console.error('loadCounselorData 函数不存在!');
// 尝试重新查找函数
const newScripts = document.getElementById('content-area').getElementsByTagName('script');
for (let script of newScripts) {
eval(script.textContent);
}
// 再次尝试
if (typeof loadCounselorData === 'function') {
loadCounselorData(id);
}
}
}, 100);
window.hideLoading();
} catch (error) {
console.error('加载编辑咨询师表单失败:', error);
window.showError('加载失败:' + error.message);
window.hideLoading();
}
}
// 页面加载完成后绑定按钮事件
document.addEventListener('DOMContentLoaded', function() {
// 使用事件委托监听所有禁用按钮点击
document.addEventListener('click', function(e) {
// 检查是否点击了禁用按钮
if (e.target.classList.contains('disable-btn') ||
e.target.closest('.disable-btn')) {
e.preventDefault();
e.stopPropagation();
const btn = e.target.classList.contains('disable-btn')
? e.target
: e.target.closest('.disable-btn');
const id = btn.getAttribute('data-id');
console.log('禁用按钮点击,ID:', id);
// 调用全局函数或直接处理
if (window.handleDisableCounselor) {
window.handleDisableCounselor(id);
} else {
// 直接处理
handleDisableButtonClick(id);
}
}
});
console.log('按钮事件监听器已绑定');
});
// 处理禁用按钮点击
async function handleDisableButtonClick(id) {
console.log('处理禁用按钮点击,ID:', id);
if (confirm('确定要禁用这个咨询师吗?')) {
try {
const response = await fetch('/admin/counselors/' + id + '/status', {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({status: 'DISABLED'})
});
const data = await response.json();
if (data.success) {
alert('已禁用');
// 刷新页面
if (window.loadCounselorList) {
window.loadCounselorList();
} else if (window.loadPage) {
window.loadPage('counselor-manage');
}
} else {
alert('操作失败: ' + (data.message || '未知错误'));
}
} catch (error) {
console.error('禁用失败:', error);
alert('禁用失败: ' + error.message);
}
}
}
// 导出到全局
window.handleDisableButtonClick = handleDisableButtonClick;
// 导出到全局
window.loadCounselorList = loadCounselorList;
window.loadAddCounselor = loadAddCounselor;
window.loadEditCounselor = loadEditCounselor;
console.log('counselor-manager.js 执行完成');
// static/js/modules/video-manager.js
console.log('✅ video-manager.js 加载成功');
// 视频管理模块
window.videosData = [];
async function loadVideoList() {
try {
window.showLoading();
const response = await fetch('/admin/videos/list-view');
const html = await response.text();
document.getElementById('content-area').innerHTML = html;
console.log('视频列表加载完成');
// ⭐⭐⭐ 关键:执行片段中的脚本 ⭐⭐⭐
executeFragmentScripts();
} catch (error) {
console.error('加载视频列表失败:', error);
window.showError('加载失败:' + error.message);
}
}
// 执行片段中的脚本
function executeFragmentScripts() {
setTimeout(() => {
const contentArea = document.getElementById('content-area');
if (!contentArea) return;
const scripts = contentArea.getElementsByTagName('script');
console.log('找到的内联脚本数量:', scripts.length);
// 将HTMLCollection转换为数组
const scriptsArray = Array.from(scripts);
scriptsArray.forEach(script => {
try {
// 创建新script元素执行
const newScript = document.createElement('script');
// 如果有src属性,复制src
if (script.src) {
newScript.src = script.src;
// 异步加载外部脚本
newScript.async = false;
} else {
// 内联脚本直接复制内容
newScript.textContent = script.textContent;
}
// 添加到body执行
document.body.appendChild(newScript);
console.log('执行脚本成功');
// 移除旧的script标签(可选)
script.parentNode?.removeChild(script);
} catch (error) {
console.error('执行脚本失败:', error);
}
});
// 额外的手动绑定(备用方案)
manuallyBindEvents();
}, 100);
}
// 手动绑定事件(备用方案)
function manuallyBindEvents() {
console.log('手动绑定事件...');
// 1. 删除按钮
const deleteButtons = document.querySelectorAll('.delete-btn');
deleteButtons.forEach(btn => {
// 先移除旧的事件监听器
btn.replaceWith(btn.cloneNode(true));
});
// 重新获取并绑定
document.querySelectorAll('.delete-btn').forEach(btn => {
btn.addEventListener('click', async function(e) {
e.preventDefault();
e.stopPropagation();
const id = this.getAttribute('data-id');
const title = this.getAttribute('data-title');
console.log('删除按钮点击,ID:', id, 'Title:', title);
if (!confirm(`确定要删除视频"${title}"吗?`)) {
return;
}
try {
window.showLoading();
const response = await fetch(`/admin/videos/${id}`, {
method: 'DELETE',
headers: { 'Accept': 'application/json' }
});
const result = await response.json();
if (result.success) {
alert('删除成功!');
loadVideoList(); // 重新加载列表
} else {
alert('删除失败: ' + result.message);
window.showError('删除失败: ' + result.message);
}
} catch (error) {
console.error('删除错误:', error);
alert('删除失败: ' + error.message);
window.showError('删除失败: ' + error.message);
}
});
});
// 2. 编辑按钮
const editButtons = document.querySelectorAll('.edit-btn');
editButtons.forEach(btn => {
btn.replaceWith(btn.cloneNode(true));
});
document.querySelectorAll('.edit-btn').forEach(btn => {
btn.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
const id = this.getAttribute('data-id');
console.log('编辑按钮点击,ID:', id);
// 调用全局的editVideo函数
if (window.editVideo) {
window.editVideo(id);
} else {
console.error('editVideo函数未找到');
alert('编辑功能暂不可用');
}
});
});
// 3. 封面图片错误处理
document.querySelectorAll('.cover-image').forEach(img => {
img.addEventListener('error', function() {
this.onerror = null;
this.src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="80" height="45"><rect width="100%" height="100%" fill="%23f0f0f0"/><text x="50%" y="50%" font-size="12" text-anchor="middle" dy=".3em" fill="%23999">无封面</text></svg>';
});
// 立即触发错误检查
if (img.src === '#' || img.src.includes('#')) {
img.dispatchEvent(new Event('error'));
}
});
console.log('✅ 手动绑定完成');
}
// static/js/modules/video-manager.js
async function loadAddVideo() {
try {
window.showLoading();
const response = await fetch('/admin/videos/add-view');
const html = await response.text();
document.getElementById('content-area').innerHTML = html;
console.log('添加视频表单加载完成');
// ⭐⭐⭐ 关键修复:手动执行脚本 ⭐⭐⭐
setTimeout(() => {
const scripts = document.getElementById('content-area').getElementsByTagName('script');
console.log('找到的内联脚本数量:', scripts.length);
for (let script of scripts) {
try {
// 创建新script元素执行
const newScript = document.createElement('script');
if (script.src) {
newScript.src = script.src;
} else {
newScript.textContent = script.textContent;
}
document.body.appendChild(newScript);
console.log('执行脚本成功');
} catch (error) {
console.error('执行脚本失败:', error);
}
}
}, 100);
} catch (error) {
console.error('加载添加视频表单失败:', error);
window.showError('加载失败:' + error.message);
}
}
async function editVideo(id) {
try {
window.showLoading();
const response = await fetch(/admin/videos/${id}/edit-view);
const html = await response.text();
document.getElementById('content-area').innerHTML = html;
console.log('编辑视频表单加载完成,ID:', id);
// ⭐⭐⭐ 关键:执行编辑页面的脚本并绑定事件 ⭐⭐⭐
setTimeout(() => {
executeEditFormScripts(id);
}, 100);
} catch (error) {
console.error('加载编辑视频表单失败:', error);
window.showError('加载失败:' + error.message);
}
}
// 执行编辑表单的脚本并绑定事件
function executeEditFormScripts(videoId) {
console.log('执行编辑表单脚本,视频ID:', videoId);
// 1. 执行片段中的脚本
const contentArea = document.getElementById('content-area');
if (!contentArea) return;
const scripts = contentArea.getElementsByTagName('script');
const scriptsArray = Array.from(scripts);
scriptsArray.forEach(script => {
try {
const newScript = document.createElement('script');
newScript.textContent = script.textContent;
document.body.appendChild(newScript);
script.parentNode?.removeChild(script);
} catch (error) {
console.error('执行脚本失败:', error);
}
});
// 2. 手动绑定编辑表单事件
bindEditFormEvents(videoId);
}
// 绑定编辑表单事件
function bindEditFormEvents(videoId) {
console.log('绑定编辑表单事件,ID:', videoId);
// 使用正确的选择器
const saveBtn = document.getElementById('editSaveBtn');
const deleteBtn = document.getElementById('editDeleteBtn');
const backBtn = document.getElementById('editBackBtn');
if (!saveBtn) {
console.error('未找到保存按钮 editSaveBtn');
// 尝试其他选择器
const saveButtons = document.querySelectorAll('button');
saveButtons.forEach(btn => {
if (btn.textContent.includes('保存修改')) {
console.log('找到文本为"保存修改"的按钮:', btn);
}
});
return;
}
console.log('找到保存按钮:', saveBtn);
// 1. 保存按钮事件
saveBtn.addEventListener('click', async function(e) {
e.preventDefault();
console.log('保存按钮点击,视频ID:', videoId);
// 收集表单数据
const videoIdInput = document.getElementById('editVideoId');
const titleInput = document.getElementById('editVideoTitle');
const descriptionInput = document.getElementById('editVideoDescription');
const tagsInput = document.getElementById('editVideoTags');
const videoFileInput = document.getElementById('editVideoFile');
const coverFileInput = document.getElementById('editCoverFile');
if (!videoIdInput || !titleInput || !tagsInput) {
alert('表单元素缺失');
return;
}
const title = titleInput.value.trim();
const description = descriptionInput.value.trim();
const tags = tagsInput.value.trim();
if (!title || !tags) {
alert('请填写标题和标签');
return;
}
// 显示保存中
this.disabled = true;
const originalText = this.innerHTML;
this.innerHTML = '<i class="bi bi-hourglass-split"></i> 保存中...';
try {
// 创建FormData
const formData = new FormData();
formData.append('id', videoIdInput.value);
formData.append('title', title);
formData.append('description', description);
formData.append('tags', tags);
// 添加文件(如果选择了新文件)
if (videoFileInput.files[0]) {
formData.append('videoFile', videoFileInput.files[0]);
}
if (coverFileInput.files[0]) {
formData.append('coverFile', coverFileInput.files[0]);
}
console.log('发送编辑请求,ID:', videoId);
// 发送请求
const response = await fetch(`/admin/videos/${videoId}`, {
method: 'POST',
body: formData
});
console.log('响应状态:', response.status);
if (!response.ok) {
throw new Error(`HTTP错误 ${response.status}`);
}
const result = await response.json();
console.log('编辑结果:', result);
if (result.success) {
alert('✅ 视频更新成功!');
// 返回视频列表
if (window.loadVideoList) {
window.loadVideoList();
}
} else {
alert('❌ 更新失败:' + result.message);
this.disabled = false;
this.innerHTML = originalText;
}
} catch (error) {
console.error('保存失败:', error);
alert('❌ 保存失败:' + error.message);
this.disabled = false;
this.innerHTML = originalText;
}
});
// 2. 删除按钮事件
if (deleteBtn) {
deleteBtn.addEventListener('click', function(e) {
e.preventDefault();
const id = this.getAttribute('data-id');
const title = this.getAttribute('data-title');
if (confirm(`确定要删除视频"${title}"吗?`)) {
window.deleteVideo(id, title);
}
});
}
// 3. 返回按钮事件
if (backBtn) {
backBtn.onclick = function() {
if (window.loadVideoList) {
window.loadVideoList();
}
};
}
console.log('✅ 编辑表单事件绑定完成');
}
// 提交编辑表单
async function submitEditForm(form, videoId) {
console.log('提交编辑表单,ID:', videoId);
const formData = new FormData(form);
const submitBtn = form.querySelector('button[type="submit"]');
const originalText = submitBtn.innerHTML;
// 禁用提交按钮
submitBtn.disabled = true;
submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 保存中...';
try {
console.log('发送编辑请求到 /admin/videos/' + videoId);
// 注意:后端控制器使用的是 POST 方法,不是 PUT
const response = await fetch(`/admin/videos/${videoId}`, {
method: 'POST', // 使用POST方法
body: formData
});
console.log('编辑响应状态:', response.status);
if (!response.ok) {
throw new Error(`HTTP错误 ${response.status}`);
}
const result = await response.json();
console.log('编辑响应结果:', result);
if (result.success) {
alert('✅ 视频更新成功!');
// 返回视频列表
window.loadVideoList();
} else {
alert('❌ 更新失败:' + result.message);
submitBtn.disabled = false;
submitBtn.innerHTML = originalText;
}
} catch (error) {
console.error('编辑提交失败:', error);
alert('❌ 提交失败:' + error.message);
submitBtn.disabled = false;
submitBtn.innerHTML = originalText;
}
}
async function deleteVideo(id, title) {
if (!confirm(确定要删除视频"${title}"吗?此操作不可恢复!)) {
return;
}
try {
window.showLoading();
const response = await fetch(`/admin/videos/${id}`, {
method: 'DELETE'
});
const result = await response.json();
if (result.success) {
alert(result.message);
await loadVideoList();
} else {
alert('删除失败:' + result.message);
}
} catch (error) {
console.error('删除视频失败:', error);
window.showError('删除失败:' + error.message);
}
}
// 全局删除函数
window.handleDeleteVideo = async function(id, title) {
console.log('处理删除视频:', id, title);
if (!confirm(`确定要删除视频"${title}"吗?此操作不可恢复!`)) {
return;
}
try {
window.showLoading();
const response = await fetch(`/admin/videos/${id}`, {
method: 'DELETE'
});
const result = await response.json();
if (result.success) {
alert(result.message);
await loadVideoList(); // 重新加载列表
} else {
alert('删除失败:' + result.message);
}
} catch (error) {
console.error('删除视频失败:', error);
alert('删除失败:' + error.message);
}
};
// 全局编辑函数
window.handleEditVideo = function(id) {
console.log('处理编辑视频:', id);
window.editVideo(id);
};
// 导出到全局
window.loadAddVideo = loadAddVideo;
window.editVideo = editVideo;
window.deleteVideo = deleteVideo;
console.log('video-manager.js 执行完成');
// static/js/admin-router.js
console.log('✅ admin-router.js 加载成功');
// ============ 页面路由 ============
async function loadPage(page) {
console.log('加载页面:', page);
window.currentPage = page;
window.showLoading();
updatePageTitle(page);
updateHeaderActions(page);
try {
switch(page) {
case 'dashboard':
await loadDashboard();
break;
case 'video-list':
case 'video-manage':
await loadVideoList();
break;
case 'counselor-manage':
await loadCounselorList();
break;
case 'question-manage': // 新增:题库管理
await loadQuestionList();
break;
case 'statistics':
showNotImplemented('数据统计');
break;
default:
showNotImplemented('未知页面');
}
} catch (error) {
console.error('加载页面失败:', error);
window.showError('加载失败:' + error.message);
}
}
async function loadQuestionList() {
try {
console.log('加载题目列表...');
const response = await fetch('/admin/questions/list-view');
if (!response.ok) {
throw new Error(`HTTP错误 ${response.status}`);
}
const html = await response.text();
const contentArea = document.getElementById('content-area');
if (contentArea) {
contentArea.innerHTML = html;
console.log('HTML已插入');
}
} catch (error) {
console.error('加载题目列表失败:', error);
showError('加载题目列表失败:' + error.message);
}
}
// ============ 页面标题管理 ============
function updatePageTitle(page) {
const titles = {
'dashboard': { title: '仪表盘', desc: '系统概览和数据统计' },
'video-manage': { title: '学习内容管理', desc: '管理心理视频、学习包、测试题等内容' },
'video-list': { title: '视频管理', desc: '管理所有视频内容' },
'counselor-manage': { title: '咨询师管理', desc: '管理咨询师账号和服务信息' },
'learning-packages': { title: '学习包管理', desc: '管理心理学习包' },
'question-manage': { title: '题库管理', desc: '添加、修改测试题目' }, // 新增
'statistics': { title: '数据统计', desc: '查看系统数据报表' }
};
const title = titles[page] || titles['dashboard'];
const pageTitle = document.getElementById('page-title');
const pageDesc = document.getElementById('page-desc');
if (pageTitle) {
pageTitle.textContent = title.title;
} else {
console.warn('未找到 page-title 元素');
}
if (pageDesc) {
pageDesc.textContent = title.desc;
} else {
console.warn('未找到 page-desc 元素');
}
}
// ============ 更新头部按钮 ============
function updateHeaderActions(page) {
const headerActions = document.getElementById('header-actions');
if (!headerActions) {
console.warn('未找到 header-actions 元素');
return;
}
if (page === 'video-list' || page === 'video-manage') {
headerActions.innerHTML = `
<button class="btn btn-primary" onclick="window.loadAddVideo ? window.loadAddVideo() : alert('功能暂不可用')">
<i class="bi bi-plus-circle"></i> 上传视频
</button>
`;
} else if (page === 'counselor-manage') {
headerActions.innerHTML = `
<button class="btn btn-primary" onclick="window.loadAddCounselor ? window.loadAddCounselor() : alert('功能暂不可用')">
<i class="bi bi-person-plus"></i> 添加咨询师
</button>
`;
} else if (page === 'question-manage') { // 新增:题库管理的头部按钮
headerActions.innerHTML = `
<button class="btn btn-primary" onclick="loadAddQuestion()">
<i class="bi bi-plus-circle"></i> 添加题目
</button>
`;
} else {
headerActions.innerHTML = '';
}
}
// ============ 页面加载函数 ============
async function loadDashboard() {
const contentArea = document.getElementById('content-area');
if (contentArea) {
contentArea.innerHTML = `
0
视频总数
0
启用中
0
总播放量
0
分类数量
<div class="card mt-4">
<div class="card-header">
<h5 class="mb-0">系统概览</h5>
</div>
<div class="card-body">
<p>欢迎使用心理视频管理系统</p>
<p>请从左侧菜单选择功能</p>
</div>
</div>
`;
}
}
// ============ 视频管理相关函数 ============
async function loadVideoList() {
try {
console.log('加载视频列表...');
const response = await fetch('/admin/videos/list-view');
if (!response.ok) {
throw new Error(`HTTP错误 ${response.status}`);
}
const html = await response.text();
const contentArea = document.getElementById('content-area');
if (contentArea) {
contentArea.innerHTML = html;
console.log('视频列表加载成功');
}
} catch (error) {
console.error('加载视频列表失败:', error);
showError('加载视频列表失败:' + error.message);
}
}
// ============ 咨询师管理相关函数 ============
async function loadCounselorList() {
try {
console.log('加载咨询师列表...');
const response = await fetch('/admin/counselors/list-view');
if (!response.ok) {
throw new Error(`HTTP错误 ${response.status}`);
}
const html = await response.text();
const contentArea = document.getElementById('content-area');
if (contentArea) {
contentArea.innerHTML = html;
console.log('咨询师列表加载成功');
}
} catch (error) {
console.error('加载咨询师列表失败:', error);
showError('加载咨询师列表失败:' + error.message);
}
}
// 添加编辑咨询师页面加载(如果需要直接访问)
async function loadEditCounselor(id) {
try {
window.showLoading();
const response = await fetch(/admin/counselors/${id}/edit-view);
const html = await response.text();
document.getElementById('content-area').innerHTML = html;
console.log('编辑咨询师页面加载成功');
} catch (error) {
console.error('加载编辑咨询师页面失败:', error);
showError('加载失败:' + error.message);
}
}
// 导出到全局
window.loadEditCounselor = loadEditCounselor;
// ============ 未实现功能 ============
function showNotImplemented(feature) {
const contentArea = document.getElementById('content-area');
if (contentArea) {
contentArea.innerHTML = <div class="empty-state"> <i class="bi bi-tools"></i> <h3>${feature}功能开发中</h3> <p>该功能正在紧张开发中,敬请期待...</p> <button class="btn btn-primary mt-3" onclick="loadPage('dashboard')"> <i class="bi bi-arrow-left"></i> 返回仪表盘 </button> </div> ;
}
}
// ============ 题目功能 ============
// 新增:添加题目页面
// 在 admin-router.js 的 loadAddQuestion 函数中修改
function loadAddQuestion() {
window.showLoading();
console.log('加载添加题目页面...');
fetch('/admin/questions/add-view')
.then(response => response.text())
.then(html => {
const contentArea = document.getElementById('content-area');
if (contentArea) {
contentArea.innerHTML = html;
console.log('HTML已插入');
// 动态添加JavaScript函数
addQuestionFunctions();
}
})
.catch(error => {
console.error('加载添加题目页面失败:', error);
window.showError('加载失败');
});
}
// 添加题目相关的JavaScript函数
function addQuestionFunctions() {
console.log('正在添加题目表单的JavaScript函数...');
// 1. 保存题目函数
// 在 admin-router.js 的 saveQuestion 函数中修改
window.saveQuestion = function() {
console.log('💾 保存题目按钮被点击');
// 获取表单数据 - 添加详细日志
const questionTextEl = document.getElementById('questionText');
const questionText = questionTextEl ? questionTextEl.value.trim() : '';
console.log('📝 题目内容原始值:', questionTextEl?.value);
console.log('📝 题目内容修剪后:', questionText);
if (!questionText) {
alert('请填写题目内容!');
questionTextEl?.focus();
return;
}
const questionData = {
question_text: questionText,
question_type: document.getElementById('questionType')?.value || 'SINGLE_CHOICE',
difficulty: document.getElementById('difficulty')?.value || 'MEDIUM',
explanation: document.getElementById('explanation')?.value?.trim() || '',
is_active: document.getElementById('isActive')?.checked || true
};
console.log('📋 表单数据对象:', questionData);
console.log('📋 表单数据JSON:', JSON.stringify(questionData));
// 处理选项
const optionA = document.getElementById('optionA')?.value?.trim() || '选项A';
const optionB = document.getElementById('optionB')?.value?.trim() || '选项B';
if (questionData.question_type === 'SINGLE_CHOICE' || questionData.question_type === 'MULTIPLE_CHOICE') {
questionData.options = {
'A': optionA,
'B': optionB
};
// 获取正确答案
if (questionData.question_type === 'SINGLE_CHOICE') {
const selected = document.querySelector('input[name="correctOption"]:checked');
questionData.correct_answer = selected ? selected.value : 'A';
console.log('✅ 单选题正确答案:', questionData.correct_answer);
}
} else if (questionData.question_type === 'TRUE_FALSE') {
questionData.options = { 'A': '正确', 'B': '错误' };
const selected = document.querySelector('input[name="correctOption"]:checked');
questionData.correct_answer = selected ? selected.value : 'A';
console.log('✅ 判断题正确答案:', questionData.correct_answer);
}
console.log('🚀 最终发送数据:', JSON.stringify(questionData, null, 2));
// 发送请求
fetch('/admin/questions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(questionData)
})
.then(response => {
console.log('📨 响应状态:', response.status, response.statusText);
return response.json();
})
.then(result => {
console.log('✅ 服务器响应:', result);
if (result.success) {
alert('保存成功!');
loadPage('question-manage');
} else {
alert('保存失败: ' + (result.message || '未知错误'));
}
})
.catch(error => {
console.error('❌ 请求失败:', error);
alert('保存失败');
});
};
// 2. 返回列表函数
window.goBack = function() {
loadPage('question-manage');
};
// 3. 重置表单函数
window.resetForm = function() {
if (confirm('确定要重置表单吗?')) {
document.getElementById('questionText').value = '';
document.getElementById('explanation').value = '';
document.getElementById('optionA').value = '选项A';
document.getElementById('optionB').value = '选项B';
document.getElementById('isActive').checked = true;
}
};
console.log('✅ 题目表单函数添加完成');
console.log('saveQuestion函数:', typeof window.saveQuestion);
// 在 admin-router.js 文件末尾添加这个函数
function fixQuestionFunctions() {
console.log('🛠️ 修复题目管理函数...');
// 检查关键函数是否存在
if (typeof window.loadQuestionData === 'undefined') {
console.log('⚠️ loadQuestionData 未定义,重新注入...');
// 重新注入函数
if (typeof injectQuestionFunctions === 'function') {
injectQuestionFunctions();
} else {
console.error('❌ injectQuestionFunctions 函数不存在');
// 紧急修复:直接定义必要函数
defineEmergencyQuestionFunctions();
}
}
// 检查是否在题目管理页面
const questionTableBody = document.getElementById('questionTableBody');
if (questionTableBody && window.currentPage === 'question-manage') {
console.log('📋 在题目管理页面,检查表格状态...');
// 如果表格还是加载中状态,强制重新加载
if (questionTableBody.innerHTML.includes('spinner-border')) {
console.log('🔄 表格仍在加载中,手动加载数据...');
setTimeout(() => {
if (window.loadQuestionData) {
window.loadQuestionData(1);
}
}, 500);
}
}
}
}
// ============ 导出到全局 ============
window.loadPage = loadPage;
window.updatePageTitle = updatePageTitle;
window.updateHeaderActions = updateHeaderActions;
window.loadDashboard = loadDashboard;
window.loadVideoList = loadVideoList;
window.loadCounselorList = loadCounselorList;
window.showNotImplemented = showNotImplemented;
window.loadAddQuestion = loadAddQuestion;
window.loadQuestionList = loadQuestionList;
window.fixQuestionFunctions = fixQuestionFunctions;
window.defineEmergencyQuestionFunctions = defineEmergencyQuestionFunctions;
window.renderEmergencyQuestionTable = renderEmergencyQuestionTable;
console.log('admin-router.js 执行完成');

浙公网安备 33010602011771号