// 自定义JavaScript函数 // 显示加载动画 function showLoading() { const loadingElement = document.getElementById('loading'); if (loadingElement) { loadingElement.style.display = 'block'; } } // 隐藏加载动画 function hideLoading() { const loadingElement = document.getElementById('loading'); if (loadingElement) { loadingElement.style.display = 'none'; } } // 显示通知 function showNotification(message, type = 'info') { // 创建通知元素 const alertDiv = document.createElement('div'); alertDiv.className = `alert alert-${type} alert-dismissible fade show`; alertDiv.innerHTML = ` ${message} `; // 插入到页面中 const container = document.querySelector('main') || document.body; container.insertBefore(alertDiv, container.firstChild); // 5秒后自动隐藏 setTimeout(() => { if (alertDiv.parentNode) { alertDiv.remove(); } }, 5000); } // 格式化日期 function formatDate(dateString) { if (!dateString) return '-'; const date = new Date(dateString); return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN'); } // 格式化文件大小 function formatFileSize(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } // API请求函数 - 添加认证支持 function apiRequest(url, options = {}) { // 确保URL是完整的路径 let fullUrl = url; if (!url.startsWith('/')) { fullUrl = '/' + url; } if (!url.startsWith('/api/')) { fullUrl = '/api/v1' + fullUrl; } if (!url.startsWith('/')) { fullUrl = '/' + fullUrl; } // 设置默认选项 const defaultOptions = { headers: { 'Content-Type': 'application/json', }, credentials: 'same-origin' // 确保发送cookies进行认证 }; // 合并选项 const mergedOptions = { ...defaultOptions, ...options, headers: { ...defaultOptions.headers, ...options.headers } }; // 显示加载动画 showLoading(); // 发起请求 return fetch(fullUrl, mergedOptions) .then(response => { // 隐藏加载动画 hideLoading(); // 检查响应状态 if (response.status === 401) { // 未授权,重定向到登录页面 window.location.href = '/login'; throw new Error('未授权访问'); } return response.json().catch(() => ({})); }) .catch(error => { // 隐藏加载动画 hideLoading(); // 处理网络错误 console.error('API请求失败:', error); throw error; }); }