You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript将HTML表单数据以data.json文件发送至REST API

解决方案:将HTML表单数据转为指定JSON格式发送至REST API

优化后的完整代码

<body>
    <form id="profile-form">
        <input type="text" id="name" name="name" placeholder="Name" required>
        <input type="email" id="email" name="email" placeholder="Email Address" required>
        <button type="submit">Submit</button>
    </form>

<script>
    const form = document.querySelector('#profile-form');
    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        // 从表单自动收集所有带name属性的字段数据
        const formData = new FormData(form);
        // 转换为目标结构的JSON对象
        const jsonData = Object.fromEntries(formData);

        try {
            const response = await fetch('你的REST API端点URL', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(jsonData)
            });

            // 检查请求是否成功
            if (!response.ok) {
                throw new Error(`请求失败,状态码:${response.status}`);
            }

            const result = await response.json();
            console.log('发送成功:', result);
        } catch (err) {
            console.error('发送出错:', err);
        }
    });
</script> 
</body>

关键修改说明

  • 简化数据收集:通过new FormData(form)自动抓取表单数据,无需逐个获取input元素,后续新增字段无需修改JS代码。
  • 移除无效配置:删除fetch不支持的dataType参数;若API允许跨域访问,建议移除mode: 'no-cors'(该模式会导致无法读取响应内容)。
  • 规范JSON格式:Object.fromEntries(formData)直接将FormData转为键值对对象,JSON.stringify()后即可生成要求的{"name":"xxx","email":"xxx"}结构。
  • 优化异步逻辑:用async/await替代链式.then(),代码可读性更强,错误处理更直观。
  • 增强基础验证:给input添加required属性,前端先拦截空数据提交。

注意事项

无需在本地创建物理data.json文件,上述代码直接在内存中生成JSON字符串并发送,完全符合需求。若API要求标识数据为data.json,可在请求头或后端约定的参数中补充标识。

内容的提问来源于stack exchange,提问作者Akash M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 22:07:48