新闻中心

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

2025-10-08
浏览次数:
返回列表

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

本文档旨在解决Spring项目中,删除数据库条目后,前端页面需要刷新才能显示最新数据的问题。通过修改删除操作后的处理逻辑,利用J*aScript操作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,方便后续通过 J*aScript 找到并删除它。

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写作辅助平台

青泥AI 360 查看详情 青泥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. 完整代码示例

下面是修改后的完整 J*aScript 代码:

    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。
  • 在删除操作后,通过 J*aScript 找到对应的 HTML 元素并将其删除。
  • 确保服务器端返回被删除条目的 ID。

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

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


# 如何在  # 钦州市场营销获客推广招聘  # 云南品牌推广营销案例  # 四川建设集团网站  # 鸡蛋的seo优化方式  # 丹东seo排名推荐企业  # seo如何优化网站推广  # 昌乐网站推广优化价格  # seo系统培训班  # seo点击软件找名风  # seo优化课程推广  # 将其  # 在这个  # 是因为  # 加载  # 移除  # javascript  # 这一行  # 表单  # 置顶  # win  # 后端  # ssl  # app  # node  # json  # 前端  # js  # html  # java  # word 


相关栏目: 【 科技资讯46185 】 【 网络学院92790


相关推荐: React列表渲染与独立状态管理:避免全局状态影响局部更新  html怎么运行外部js文件中的函数_运html外js文件函数法【技巧】  J*aScript中针对特定容器内图片动画的实现教程  抖音网页版快捷访问 抖音网页版网页版入口操作教程  MongoDB Aggregation:在嵌套对象数组中精确匹配ObjectId  服务端验证_j*ascript输入检查  双系统安装时,如何设置默认启动系统? msconfig命令了解一下!  单12V-2&#215;6实现为RTX 5090供电750W!甚至都没敢跑分  C++20的source_location是什么_C++在编译期获取源码位置信息用于日志和断言  漫蛙manwa2最新登录网址_漫蛙manwa2手机网页版入口  NetBeans Ant项目:自动化将资源文件复制到dist目录的教程  聚水潭ERP登录页面入口 聚水潭ERP官网登录界面  狙击外星人小游戏开始_狙击外星人小游戏立即开始  天眼查怎么看公司融资情况 天眼查企业融资历史查询步骤【攻略】  sublime怎么设置启动时打开的窗口_sublime会话管理与热退出  护手霜蹭到袖口上了如何清洗? 怎样避免留下一圈油印?  GemBox Document HTML转PDF垂直文本渲染问题及解决方案  J*aScript动态修改指定div内所有a标签样式指南  探索高级语言到原生C/C++的转译:挑战与内存管理策略  Windows 11怎么彻底关闭定位_Windows 11服务中禁用Geolocation  Spring Boot内嵌服务器与J*a EE全栈特性:选择与部署策略  c++中的std::forward_list和std::list有什么不同_c++ forward_list与list区别分析  qq游戏网页版直接玩_qq游戏免下载快速入口  微博网页版官方账号登录 微博网页版内容浏览使用指南  HuggingFaceEmbeddings中向量嵌入维度调整的限制与理解  Win11怎么修改默认浏览器_Windows 11设置Chrome为默认  MAC怎么让Dock栏只显示当前运行的应用_MAC终端命令实现极简Dock栏  C++如何打印当前代码行号与文件名_C++预定义宏FILE与LINE的使用  Golang如何处理RPC请求负载均衡_Golang RPC请求负载均衡策略与实践  深入理解J*aScript中的B样条曲线与节点向量生成  在Socket.IO连接中实现Access Token自动更新与动态重连  J*aScript异步迭代器_j*ascript异步遍历  CSS条件样式无法按设备触发怎么排查_media条件语句正确设置解决触发问题  解决 Vaadin 8 中大文件音频播放与定位时出现的 IOException  4399体育竞技小游戏_4399小游戏赛事入口  J*a实现学校排课程序_面向对象结构化项目示例  Gmail邮箱申请注册直达_Gmail邮箱免费注册PC版官网入口2025  Tabulator表格中精确实现日期时间排序的指南  J*aScript教程:根据元素文本内容动态设置背景色  Golang如何实现简单的Web表单_Golang表单提交与验证处理方法  Windows10怎么开启存储感知 Windows10系统设置自动清理临时文件释放C盘空间【教程】  Win11输入法不见了怎么办_Windows11恢复语言栏显示方法  漫蛙漫画官方主页入口 漫蛙MANWA网页直达访问链接  “在文档元素之后找到了标记”是什么错误? 检查并修复XML中多个根元素的3个方法  MAC如何将整个网页截长图_MAC使用Safari的导出为PDF或第三方工具  迅雷下载到U盘速度很慢怎么办_迅雷U盘下载慢优化方法  J*a TimerTask中HashMap意外清空的深层原因与解决方案  处理Kafka消费者会话超时:深入理解消息处理语义与幂等性  QQ邮箱官网登录入口 QQ邮箱网页版邮箱快速登录  J*aScript:在map操作中高效处理空数组 

搜索