API调用时添加加载遮罩动画及错误提示的实现方法
实现加载遮罩与错误提示的方案
1. 添加页面元素
先在HTML中加入加载遮罩和错误提示的容器:
<!-- 加载遮罩 --> <div id="loading-overlay" style="display: none;"> <div class="loading-content">加载中...</div> </div> <!-- 错误提示框 --> <div id="error-toast" style="display: none;"> <span id="error-message"></span> <button onclick="hideError()">关闭</button> </div>
2. 编写样式
添加CSS实现全屏遮罩和错误提示的视觉效果:
#loading-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 9999; cursor: wait; } .loading-content { background: white; padding: 20px 40px; border-radius: 8px; font-size: 18px; } #error-toast { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background-color: #dc3545; color: white; padding: 12px 24px; border-radius: 4px; z-index: 10000; display: flex; gap: 16px; align-items: center; } #error-toast button { background: transparent; border: none; color: white; font-size: 20px; cursor: pointer; }
3. 修改API调用函数
更新原函数,集成加载状态控制和错误处理逻辑:
window.onload = getPlatforms; // 隐藏错误提示的辅助函数 function hideError() { document.getElementById('error-toast').style.display = 'none'; } async function getPlatforms() { const loadingOverlay = document.getElementById('loading-overlay'); const errorToast = document.getElementById('error-toast'); const errorMessage = document.getElementById('error-message'); try { // 显示加载遮罩,隐藏错误提示 loadingOverlay.style.display = 'flex'; errorToast.style.display = 'none'; const response = await fetch( 'http://10.64.127.94:5000/api/get_platforms', { method: 'POST' } ); // 处理HTTP错误(比如404、500) if (!response.ok) { throw new Error(`请求失败:${response.status} ${response.statusText}`); } const jdata = await response.json(); const ldata = jdata["final_result"]; // 声明变量,避免全局污染 const selectElement = document.getElementById('device_select'); // 清空原有选项再添加(避免重复) selectElement.innerHTML = ''; selectElement.appendChild(new Option("SELECT", "SELECT")); for (const item of ldata) { selectElement.appendChild(new Option(item, item)); } ClearOptionsFast("label_select"); ClearOptionsFast("baseline_select"); } catch (error) { // 显示错误信息 errorMessage.textContent = error.message || '网络异常,请稍后重试'; errorToast.style.display = 'flex'; } finally { // 无论成功失败,都隐藏加载遮罩 loadingOverlay.style.display = 'none'; } }
关键说明
- 加载遮罩:通过
fixed定位覆盖整个页面,半透明背景阻止用户点击下层元素,cursor: wait提示用户当前处于加载状态。 - 错误处理:用
try-catch捕获网络错误,同时通过response.ok判断HTTP请求是否成功,覆盖所有可能的错误场景。 - 代码优化:添加变量声明避免全局污染,清空下拉框原有选项再添加新内容,防止重复填充。
内容的提问来源于stack exchange,提问作者Akshay J
相关产品推荐
相关产品推荐

