| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- // 获取文档结构
- 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);
- });
- }
- // 页面加载时执行
- document.addEventListener('DOMContentLoaded', loadDocumentStructure);
|