如何在Spring项目中实现表单或字段集的局部刷新

霞舞
发布: 2025-10-08 10:02:28
原创
960人浏览过

如何在spring项目中实现表单或字段集的局部刷新

本文档旨在解决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 中移除。如果没有找到该元素,则在控制台输出警告信息。

表单大师AI
表单大师AI

一款基于自然语言处理技术的智能在线表单创建工具,可以帮助用户快速、高效地生成各类专业表单。

表单大师AI 74
查看详情 表单大师AI

注意: 服务器端需要确保在删除操作成功后,返回被删除条目的 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 = `
                <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})`);
    }
登录后复制

6. 总结

通过以上步骤,可以在 Spring 项目中实现删除操作后的局部刷新,避免整个页面重新加载,提升用户体验。 关键在于:

  • 在创建条目时,为每个条目添加唯一的 ID。
  • 在删除操作后,通过 JavaScript 找到对应的 HTML 元素并将其删除。
  • 确保服务器端返回被删除条目的 ID。

这样,就可以实现高效、流畅的前端更新,提升用户体验。

以上就是如何在Spring项目中实现表单或字段集的局部刷新的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号