| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- // 获取文档结构
- async function loadDocumentStructure() {
- const loading = document.getElementById('loading');
- const error = document.getElementById('error');
- const container = document.getElementById('categories-container');
- try {
- const response = await fetch('/api/structure');
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || `加载失败 (${response.status})`);
- }
- const structure = await response.json();
- // 验证数据结构
- if (!Array.isArray(structure) || structure.length === 0) {
- throw new Error('文档结构为空或格式错误');
- }
- // 隐藏加载提示
- loading.style.display = 'none';
- // 渲染分类卡片
- renderCategories(structure);
- } catch (err) {
- console.error('Error loading structure:', err);
- loading.style.display = 'none';
- error.style.display = 'block';
- error.textContent = `加载失败:${err.message || '请稍后重试'}`;
- }
- }
- // 渲染分类卡片
- function renderCategories(structure) {
- const container = document.getElementById('categories-container');
- structure.forEach(category => {
- const card = document.createElement('div');
- card.className = 'category-card';
- const title = document.createElement('h2');
- title.className = 'category-title';
- title.textContent = category.name;
- const docCount = document.createElement('p');
- docCount.className = 'doc-count';
- docCount.textContent = `${category.docs.length} 篇文档`;
- const button = document.createElement('button');
- button.className = 'read-btn';
- button.textContent = '开始阅读';
- button.onclick = () => {
- // 跳转到阅读页,并传递分类名
- window.location.href = `/reader.html?category=${encodeURIComponent(category.name)}`;
- };
- card.appendChild(title);
- card.appendChild(docCount);
- card.appendChild(button);
- container.appendChild(card);
- });
- }
- // 登出功能
- function setupLogout() {
- const logoutBtn = document.getElementById('logout-btn');
- if (logoutBtn) {
- logoutBtn.addEventListener('click', async () => {
- if (!confirm('确定要登出吗?')) {
- return;
- }
- try {
- const response = await fetch('/api/logout', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- }
- });
- if (response.ok) {
- // 登出成功,跳转到登录页
- window.location.href = '/login.html';
- } else {
- alert('登出失败,请稍后重试');
- }
- } catch (error) {
- console.error('Logout error:', error);
- alert('登出失败,请稍后重试');
- }
- });
- }
- }
- // 页面加载时执行
- document.addEventListener('DOMContentLoaded', () => {
- loadDocumentStructure();
- setupLogout();
- });
|