
在现代web应用开发中,用户体验是至关重要的。当用户执行如添加、删除或修改数据等操作时,期望页面能够即时响应,并且只更新相关联的局部内容,而不是整个页面重新加载。全页刷新不仅会中断用户的操作流程,导致表单数据丢失或滚动位置重置,还会增加服务器负载和网络带宽消耗。
本教程将以一个Spring项目中的商品列表管理为例,详细阐述如何利用JavaScript的Fetch API与DOM操作,实现删除商品后仅刷新显示列表的特定区域,而不是整个页面。
在原始的项目实现中,当用户点击“删除”按钮并成功从数据库中删除商品后,前端视图并不会立即更新。用户需要手动刷新整个页面才能看到删除后的结果。然而,这种全页刷新会导致以下问题:
为了解决这些问题,我们需要采用局部刷新的策略,即通过异步请求(AJAX)与DOM操作来更新页面内容。
实现局部刷新的核心在于:
立即学习“前端免费学习笔记(深入)”;
在我们的商品列表案例中,当删除操作成功后,后端会返回一个确认信息(通常包含被删除商品的ID),前端根据这个ID找到对应的HTML元素并将其移除或隐藏。
为了实现删除后的局部刷新,我们需要对现有代码进行以下改造:
在createNewProduct函数中,每个商品列表项(label元素)都需要一个唯一的ID,以便在删除时能够精确地找到并操作它。建议使用pid-前缀加上商品ID作为元素的ID。
原始代码片段:
function createNewProduct(product) {
const label = document.createElement('label');
// ... 其他创建子元素的代码
label.classList.add('label');
// ... 填充子元素内容
document.getElementById('allProducts').appendChild(label);
// ... 样式设置
}改造后的createNewProduct函数:
function createNewProduct(product) {
const label = document.createElement('label');
label.setAttribute('id', `pid-${product.id}`); // 添加唯一ID
const l1 = document.createElement('label');
const l2 = document.createElement('label');
const l3 = document.createElement('label');
const l4 = document.createElement('label');
label.classList.add('label');
l1.appendChild(document.createTextNode(` ID:${product.id}. `));
l2.appendChild(document.createTextNode(` ${product.name} `));
l3.appendChild(document.createTextNode(` ${product.amount} `));
l4.appendChild(document.createTextNode(` ${product.type} `));
label.appendChild(l1).appendChild(l2).appendChild(l3).appendChild(l4);
document.getElementById('allProducts').appendChild(label);
label.style.display= 'table';
label.style.paddingLeft='40%';
label.style.wordSpacing='30%';
}我们需要一个专门的函数来处理后端返回的删除成功响应,并根据响应中的ID来更新前端视图。这个函数将接收后端返回的包含被删除商品ID的对象。
deleteProduct函数:
function deleteProduct(deleteApiResponse) {
// 确保后端在删除成功后返回了被删除商品的ID
// 例如:DELETE /api/list/123 成功后,后端响应 { "id": 123, "message": "Product deleted successfully" }
const { id } = deleteApiResponse;
if (id) {
const elementIdToDel = `pid-${id}`;
const elementToRemove = document.getElementById(elementIdToDel);
if (elementToRemove) {
// 方式一:隐藏元素 (保留在DOM中,只是不可见)
elementToRemove.style.display = 'none';
// 方式二:从DOM中完全移除元素 (更彻底)
// elementToRemove.parentNode.removeChild(elementToRemove);
} else {
console.warn(`Element with ID ${elementIdToDel} not found for deletion.`);
}
} else {
console.error("No ID found in delete API response.");
}
}注意事项:
最后,我们需要修改removeTodo函数,使其在DELETE请求成功后,调用deleteProduct函数来更新前端视图。
原始removeTodo函数:
function removeTodo() {
const d = document.getElementById('idToDel').value;
fetch(`${API_URL_ALL}/${d}`, { method: 'DELETE' })
.then(processOkResponse)
.catch(console.info)
}改造后的removeTodo函数:
function removeTodo() {
const d = document.getElementById('idToDel').value;
if (!d) {
alert("Please provide an ID to delete.");
return;
}
fetch(`${API_URL_ALL}/${d}`, { method: 'DELETE' })
.then(processOkResponse)
.then(deleteProduct) // 在删除成功后调用deleteProduct更新视图
.then(() => {
document.getElementById('idToDel').value = ''; // 清空输入框
console.log(`Product with ID ${d} deleted successfully.`);
})
.catch(error => {
console.error('Error deleting product:', error);
alert('Failed to delete product. Please check console for details.');
});
}以下是整合了上述修改后的关键JavaScript代码片段:
<script>
const API_URL = 'http://localhost:8080';
const API_URL_ADD = `${API_URL}/api`;
const API_URL_ALL = `${API_URL_ADD}/list`;
const pName = document.getElementById('name');
const pUom = document.getElementById('uom');
const pAmount = document.getElementById('amount');
// 页面加载时获取所有商品并显示
fetch(API_URL_ALL)
.then(processOkResponse)
.then(list => list.forEach(createNewProduct))
.catch(console.error); // 增加错误处理
// 添加商品功能(已支持局部刷新)
document.getElementById('addProduct').addEventListener('click', (event) => {
event.preventDefault();
fetch(API_URL_ALL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: pName.value, type : pUom.value, amount: pAmount.value })
})
.then(processOkResponse)
.then(createNewProduct) // 添加成功后直接创建新元素
.then(() => {
pName.value = '';
pAmount.value = '';
pUom.value = '';
})
.catch(console.warn);
});
// 创建新的商品列表项并添加到DOM中
function createNewProduct(product) {
const label = document.createElement('label');
label.setAttribute('id', `pid-${product.id}`); // 为每个商品添加唯一ID
const l1 = document.createElement('label');
const l2 = document.createElement('label');
const l3 = document.createElement('label');
const l4 = document.createElement('label');
label.classList.add('label');
l1.appendChild(document.createTextNode(` ID:${product.id}. `));
l2.appendChild(document.createTextNode(` ${product.name} `));
l3.appendChild(document.createTextNode(` ${product.amount} `));
l4.appendChild(document.createTextNode(` ${product.type} `));
label.appendChild(l1).appendChild(l2).appendChild(l3).appendChild(l4);
document.getElementById('allProducts').appendChild(label);
label.style.display= 'table';
label.style.paddingLeft='40%';
label.style.wordSpacing='30%';
}
// 删除商品按钮事件监听
document.getElementById('delProduct').addEventListener('click', (event) => {
event.preventDefault();
removeTodo();
});
// 执行删除操作并更新视图
function removeTodo() {
const d = document.getElementById('idToDel').value;
if (!d) {
alert("Please provide an ID to delete.");
return;
}
fetch(`${API_URL_ALL}/${d}`, { method: 'DELETE' })
.then(processOkResponse)
.then(deleteProduct) // 调用deleteProduct函数更新视图
.then(() => {
document.getElementById('idToDel').value = ''; // 清空输入框
console.log(`Product with ID ${d} deleted successfully.`);
})
.catch(error => {
console.error('Error deleting product:', error);
alert('Failed to delete product. Please check console for details.');
});
}
// 根据后端响应的ID,从DOM中移除或隐藏对应的商品元素
function deleteProduct(deleteApiResponse) {
const { id } = deleteApiResponse; // 假设后端返回 { id: deletedId }
if (id) {
const elementIdToDel = `pid-${id}`;
const elementToRemove = document.getElementById(elementIdToDel);
if (elementToRemove) {
elementToRemove.style.display = 'none'; // 隐藏元素
// 或者 elementToRemove.parentNode.removeChild(elementToRemove); // 彻底移除元素
} else {
console.warn(`Element with ID ${elementIdToDel} not found for deletion.`);
}
} else {
console.error("No ID found in delete API response. Cannot update view.");
}
}
// 处理Fetch响应,检查HTTP状态码
function processOkResponse(response = {}) {
if (response.ok) {
return response.json();
}
throw new Error(`Status not 200 (${response.status})`);
}
// ... 其他函数(如AddFunction, print-btn等)保持不变
</script>通过为动态生成的DOM元素分配唯一ID,并结合Fetch API进行异步数据交互,以及JavaScript的DOM操作,我们可以高效地实现页面的局部刷新。这种方法避免了全页刷新的性能开销和用户体验问题,使得Web应用更加流畅和响应迅速。掌握这种前端更新策略,是构建现代交互式Web应用的重要技能。
以上就是利用Fetch API与DOM操作实现Spring项目前端局部内容刷新的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号