0

0

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

霞舞

霞舞

发布时间:2025-10-08 10:02:28

|

979人浏览过

|

来源于php中文网

原创

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

OpenJobs AI
OpenJobs AI

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。

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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

161

2025.08.06

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

89

2026.01.26

json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

457

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

549

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

337

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

83

2025.09.10

数据库Delete用法
数据库Delete用法

数据库Delete用法:1、删除单条记录;2、删除多条记录;3、删除所有记录;4、删除特定条件的记录。更多关于数据库Delete的内容,大家可以访问下面的文章。

289

2023.11.13

drop和delete的区别
drop和delete的区别

drop和delete的区别:1、功能与用途;2、操作对象;3、可逆性;4、空间释放;5、执行速度与效率;6、与其他命令的交互;7、影响的持久性;8、语法和执行;9、触发器与约束;10、事务处理。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

222

2023.12.29

C++多线程并发控制与线程安全设计实践
C++多线程并发控制与线程安全设计实践

本专题围绕 C++ 在高性能系统开发中的并发控制技术展开,系统讲解多线程编程模型与线程安全设计方法。内容包括互斥锁、读写锁、条件变量、原子操作以及线程池实现机制,同时结合实际案例分析并发竞争、死锁避免与性能优化策略。通过实践讲解,帮助开发者掌握构建稳定高效并发系统的关键技术。

2

2026.03.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 6.1万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 3.5万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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