前端小案例:
案例:项目中遇到这样一个场景,在前端请求服务器获取部分资源,在等待请求回复之前,需要在前端展示一个loading,在接收到请求的回复后,就取消loading,展示资源。
当使用 fetch
请求服务器获取资源时,你可以通过以下代码来展示 loading 并在接收到响应后取消 loading,展示资源:
<!DOCTYPE html>
<html>
<head>
<title>Loading Example</title>
<style>
#loading {
display: none;
/* 样式设置为你想要的loading效果 */
}
</style>
</head>
<body>
<div id="loading">Loading...</div>
<div id="content"></div>
<script>
const loadingElement = document.getElementById('loading');
const contentElement = document.getElementById('content');
// 显示loading
function showLoading() {
loadingElement.style.display = 'block';
}
// 隐藏loading
function hideLoading() {
loadingElement.style.display = 'none';
}
// 更新内容
function updateContent(data) {
contentElement.textContent = data;
}
// 发起fetch请求
function fetchData() {
showLoading();
fetch('<http://example.com/api/resource>')
.then(response => response.text())
.then(data => {
hideLoading();
updateContent(data);
})
.catch(error => {
hideLoading();
console.error('Error:', error);
});
}
// 调用fetch请求
fetchData();
</script>
</body>
</html>
上述代码中,通过 CSS 样式将 loading 元素设置为不可见状态。在 showLoading()
函数中,将 loading 元素的样式设置为可见,显示 loading 文本或动画。
在 hideLoading()
函数中,将 loading 元素的样式设置为不可见,隐藏 loading。
updateContent()
函数用于更新内容,你可以根据实际情况将获取到的数据展示在页面的相应元素中。
在 fetchData()
函数中,首先调用 showLoading()
显示 loading,然后使用 fetch
发起请求,并在获取到响应后调用 hideLoading()
隐藏 loading,并通过 updateContent()
更新内容。如果在请求过程中出现错误,也会调用 hideLoading()
并打印错误信息。
最后,在页面加载完成后,调用 fetchData()
函数来触发请求。你可以根据实际情况调整请求的 URL 和处理响应的逻辑。
请注意,上述代码中的请求 URL http://example.com/api/resource
是一个示例,请根据你的实际需求替换为正确的请求 URL。
如果更近一步,
我在加载的过程中需要对当前的页面做一个蒙层图的操作,并且显示“展示中”,这应该如何处理?
可以查看上一篇文章 上一篇文章