
本文档旨在解决Spring项目中,删除数据库条目后,前端页面需要刷新才能显示最新数据的问题。通过修改删除操作后的处理逻辑,利用JavaScript操作DOM,实现对特定表单或字段集的局部刷新,避免整个页面重新加载,提升用户体验。
在Spring项目中,如果删除数据库中的数据后,前端页面需要刷新才能看到更新,这通常是因为删除操作后没有及时更新前端的显示。以下是如何解决这个问题,实现局部刷新的详细步骤和代码示例:
1. 修改 removeTodo 函数
目前的代码在 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 函数来更新前端。
2. 修改 createNewProduct 函数
为了方便删除特定条目,需要在创建条目时,为每个 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`。
3. 创建 deleteProduct 函数
现在需要创建一个 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。
4. 修改服务器端代码 (重要)
确保你的 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})`);}
5. 完整代码示例
下面是修改后的完整 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 = ` ${text}
`; 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})`); }
6. 总结
通过以上步骤,可以在 Spring 项目中实现删除操作后的局部刷新,避免整个页面重新加载,提升用户体验。 关键在于:
在创建条目时,为每个条目添加唯一的 ID。在删除操作后,通过 JavaScript 找到对应的 HTML 元素并将其删除。确保服务器端返回被删除条目的 ID。
这样,就可以实现高效、流畅的前端更新,提升用户体验。
以上就是如何在Spring项目中实现表单或字段集的局部刷新的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1582248.html
微信扫一扫
支付宝扫一扫