
本文档旨在解决Spring项目中,删除数据库条目后,前端页面需要刷新才能显示最新数据的问题。通过修改删除操作后的处理逻辑,利用JavaScript操作DOM,实现对特定表单或字段集的局部刷新,避免整个页面重新加载,提升用户体验。
在Spring项目中,如果删除数据库中的数据后,前端页面需要刷新才能看到更新,这通常是因为删除操作后没有及时更新前端的显示。以下是如何解决这个问题,实现局部刷新的详细步骤和代码示例:
目前的代码在 removeTodo 函数中,仅仅发送了 DELETE 请求,但没有处理请求成功后的前端更新。需要在成功删除后,更新前端的显示。
function removeTodo() {
const d = document.getElementById('idToDel').value;
fetch(`${API_URL_ALL}/${d}`, { method: 'DELETE' })
.then(processOkResponse)
.then(deleteProduct) // 添加这一行
.catch(console.info);
}这里添加了 .then(deleteProduct),表示在 processOkResponse 成功处理响应后,调用 deleteProduct 函数来更新前端。
为了方便删除特定条目,需要在创建条目时,为每个 label 元素添加一个唯一的 ID,方便后续通过 JavaScript 找到并删除它。
function createNewProduct(product) {
const label = document.createElement('label');
label.setAttribute('id', `pid-${product.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%';
}在 createNewProduct 函数中,添加了 label.setAttribute('id', \pid-${product.id}`);,为每个label元素设置了一个唯一的 ID,格式为pid-条目ID`。
现在需要创建一个 deleteProduct 函数,用于处理删除操作成功后的前端更新。这个函数接收服务器返回的响应,从中提取被删除条目的 ID,然后找到对应的 HTML 元素并将其删除。
function deleteProduct(deleteApiResponse) {
// 确保服务器返回被删除条目的 ID
const { id } = deleteApiResponse;
const idToDel = `pid-${id}`;
const elementToRemove = document.getElementById(idToDel);
if (elementToRemove) {
// 从DOM中移除该元素
elementToRemove.remove();
} else {
console.warn(`Element with id ${idToDel} not found.`);
}
}在这个函数中,首先从 deleteApiResponse 中提取被删除条目的 id。然后,使用 document.getElementById(idToDel) 找到对应的 HTML 元素。如果找到了该元素,就使用 elementToRemove.remove() 将其从 DOM 中移除。如果没有找到该元素,则在控制台输出警告信息。
注意: 服务器端需要确保在删除操作成功后,返回被删除条目的 ID。
确保你的 Spring 后端在成功删除数据后,返回被删除数据的 ID。例如,你的Controller应该返回类似如下的JSON:
{
"id": 123 // 被删除的条目ID
}如果没有返回ID,deleteProduct函数将无法工作。修改 processOkResponse 函数以适应可能的非JSON响应。
function processOkResponse(response = {}) {
if (response.ok) {
// 尝试解析 JSON,如果不是 JSON,则直接返回响应文本
return response.text().then(text => {
try {
return JSON.parse(text);
} catch (e) {
return text;
}
});
}
throw new Error(`Status not 200 (${response.status})`);
}下面是修改后的完整 JavaScript 代码:
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');
AddFunction();
fetch(API_URL_ALL)
.then(processOkResponse)
.then(list => list.forEach(createNewProduct))
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 = '')
.then(() => pAmount.value = '')
.then(() => pUom.value = '')
.catch(console.warn);
});
function createNewProduct(product) {
const label = document.createElement('label');
label.setAttribute('id', `pid-${product.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;
fetch(`${API_URL_ALL}/${d}`, { method: 'DELETE' })
.then(processOkResponse)
.then(deleteProduct) // 添加这一行
.catch(console.info);
}
function deleteProduct(deleteApiResponse) {
const { id } = deleteApiResponse;
const idToDel = `pid-${id}`;
const elementToRemove = document.getElementById(idToDel);
if (elementToRemove) {
elementToRemove.remove();
} else {
console.warn(`Element with id ${idToDel} not found.`);
}
}
function AddFunction(){
const welcomeForm = document.getElementById('welcomeForm');
document.getElementById('welcomeFormBtn').addEventListener('click', (event) => {
event.preventDefault();
const formObj = {
name: welcomeForm.elements.name.value,
};
fetch(`${API_URL_ADD}?${new URLSearchParams(formObj)}`)
.then(response => response.text())
.then((text) => {
document.getElementById('welcome').innerHTML = `
<h1>${text}</h1>
`;
welcomeForm.remove();
document.getElementById('AddForm').style.display = 'block';
});
});
}
document.getElementById('print-btn').addEventListener('click', (event) => {
event.preventDefault();
const f = document.getElementById("allProducts").innerHTML;
const a = window.open();
a.document.write(document.getElementById('welcome').innerHTML);
a.document.write(f);
a.print();
})
function processOkResponse(response = {}) {
if (response.ok) {
return response.json();
}
throw new Error(`Status not 200 (${response.status})`);
}通过以上步骤,可以在 Spring 项目中实现删除操作后的局部刷新,避免整个页面重新加载,提升用户体验。 关键在于:
这样,就可以实现高效、流畅的前端更新,提升用户体验。
以上就是如何在Spring项目中实现表单或字段集的局部刷新的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号