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


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

CA.LA CA.LA

第一款时尚产品在线设计平台,服装设计系统

CA.LA 86 查看详情 CA.LA

注意: 服务器端需要确保在删除操作成功后,返回被删除条目的 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项目中实现表单或字段集的局部刷新的详细内容,更多请关注其它相关文章!


# word  # javascript  # 表单  # win  # 后端  # ssl  # app  # node  # json  # 前端  # js  # html  # java  # seo 哪家做的好  # 湖北网络营销推广软件  # 海口网站推广工具  # 童趣网站建设银行  # 推广营销总结怎么写  # 大连市场推广营销  # 随县抖音seo公司  # 网站建设流程管理  # 巴彦淖尔昌吉网站建设  # 原创 seo 同义词 函数  # 并将其  # 将其  # 在这个  # 是因为  # 加载  # 移除  # 如何在  # 这一行 


相关栏目: 【 Google疑问12 】 【 Facebook疑问10 】 【 优化推广96088 】 【 技术知识133117 】 【 IDC资讯59369 】 【 网络运营7196 】 【 IT资讯61894


相关推荐: 热血江湖归来医师加点攻略  蛙漫2(台版)正版官网 2025免费网页版分享  J*aScript包管理器_Npm与Yarn对比  《糖豆》添加舞曲方法  掌握CSS :has() 选择器:父选择器、嵌套限制与常见陷阱解析  铁拳8在线玩 铁拳8在线秒玩入口  深入理解Python对象引用与链表属性赋值  广州地铁app准妈咪徽章领取方法  《淘宝联盟》推广自己的店铺方法  键盘测试软件哪个好_键盘故障检测工具推荐  《浙里办》电子发票开具方法  Excel宏怎么删除_Excel中删除宏的详细操作流程  如何在Golang中处理表单文件上传_Golang 表单文件上传示例  HTML中多图片上传与预览:解决ID冲突的专业指南  139邮箱登录入口官网 139邮箱登录入口官网网址  口腔诊所管理软件推荐  c++中的const关键字用法大全_c++ const正确使用指南  谷歌邮箱怎么换绑定邮箱Gmail安全备份邮箱修改方法  todesk如何添加信任设备_todesk信任设备设置教程  tiktok国际版入口_tiktok官网网页版链接  如何定制PrimeNG Sidebar的背景颜色  发布小红书怎么屏蔽粉丝?屏蔽粉丝能看到吗?  阿里云共享相册入口在哪  VS Code中的Tailwind CSS IntelliSense插件使用技巧  毒蘑菇VOLUMESHADER_BM官网首页登录入口 毒蘑菇VOLUMESHADER_BM官网首页登录入口说明  J*aScript实现下拉菜单驱动的动态表格数据展示  Python实战:高效处理实时数据流中的最小/最大值  《植物大战僵尸3》火龙草作用介绍  被称为海蜈蚣的海洋动物是  Linux如何优化系统启动流程_Linux启动项优化方案  视频转蓝光m2ts格式  深入理解J*aScript异步操作:setTimeout与调用栈的真相  j*a中ArrayBlockingQueue的使用  多闪电脑版下载_多闪PC端模拟器使用  高德地图怎么查看未来行程规划_高德地图未来行程规划查看方法  解决Windows上Composer PATH变量冲突导致的命令无法识别问题  在React中正确处理HTML input type="number"的数值类型  钉钉任务无法提醒如何处理 钉钉任务提醒优化方法  Excel如何设置动态下拉菜单_Excel表格下拉选项快速方法  12306夜间购票失败? | 查看官方公布的暂停服务公告与应对方案  胃动力不足?试试这5个调理方法  嘴唇干裂起皮怎么办 唇部护理与预防干裂的方法【详解】  LINUX怎么查看显卡信息_LINUX查看GPU状态  Magento 2 产品保存事件中安全更新属性的最佳实践  MongoDB聚合管道:高效统计列表中各项的文档数量  我的世界官方网址入口 我的世界游戏主页直达入口  b站怎么查看视频的码率_b站视频码率查看方法  苹果电脑如何快速截图并编辑 苹果电脑截屏标注快捷操作  使用 J*aScript 随机化 CSS Grid 布局中的元素顺序  手机坏了微信聊天记录怎么导出来 新手机恢复聊天记录技巧 

 2025-10-08

了解您产品搜索量及市场趋势,制定营销计划

同行竞争及网站分析保障您的广告效果

点击免费数据支持

提交您的需求,1小时内享受我们的专业解答。

运城市盐湖区信雨科技有限公司


运城市盐湖区信雨科技有限公司

运城市盐湖区信雨科技有限公司是一家深耕海外推广领域十年的专业服务商,作为谷歌推广与Facebook广告全球合作伙伴,聚焦外贸企业出海痛点,以数字化营销为核心,提供一站式海外营销解决方案。公司凭借十年行业沉淀与平台官方资源加持,打破传统外贸获客壁垒,助力企业高效开拓全球市场,成为中小企业出海的可靠合作伙伴。

 8156699

 13765294890

 8156699@qq.com

Notice

We and selected third parties use cookies or similar technologies for technical purposes and, with your consent, for other purposes as specified in the cookie policy.
You can consent to the use of such technologies by closing this notice, by interacting with any link or button outside of this notice or by continuing to browse otherwise.