使用Javascript将HTML表单数据作为file.json文件发送到REST API



寻找一个使用JavaScript将html表单数据转换为JSON文件(data.JSON(的解决方案。

目前我正在使用以下HTML&以JSON格式发送数据的JavaScript代码:

<body>
<form id="profile-form">
<input type="text" id="name" name="name" placeholder="Name">
<input type="email" id="email" name="email" placeholder="Email Address">
<button>Submit</button>
</form>
<script>
const form = document.querySelector('#profile-form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const name = document.querySelector('#name');
const email = document.querySelector('#email');
const fd = new FormData();
fd.append('name', name.value);
fd.append('email', email.value);
fetch('https://webhook.site/2d525f79-301f-4a50-b700-5ee3ba01a05c', {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify(Object.fromEntries(fd)),
dataType: 'json',
headers: {
'Content-Type': 'application/json'
//'Content-Type': 'multipart/form-data',
}
}).then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error(err));
});
</script> 
</body>

现在我希望名称和电子邮件都应该以json对象格式的data.json发送到REST API End URL。

{
"name": "abc",
"email": "abc@gmail.com"
}

注意:我无法在本地系统服务器文件中创建data.json并将其存储在本地并发送。

您可以使用JSON字符串创建自己的File对象并发送该对象。

form.addEventListener("submit", async (e) => {
e.preventDefault();
// Capture form data
const form = new FormData(e.target);
// Create a File
const file = new File(
[JSON.stringify(Object.fromEntries(form))],
"data.json",
{
type: "application/json",
}
);
// Create body for posting
const body = new FormData();
body.append("file", file); // "file" is the fieldname
const res = await fetch(
"https://webhook.site/2d525f79-301f-4a50-b700-5ee3ba01a05c",
{
method: "POST",
body,
}
);
if (!res.ok) {
throw new Error(`${res.status}: ${await res.text()}`);
}
console.log("uploaded", await res.json());
});

请记住,Fetch选项不包含dataType(该选项属于jQuery(,设置mode: "no-cors"意味着您无法看到或对响应执行任何操作。

最新更新