关联 FormData 对象和
该表单包含一个文本输入框、一个文件输入框和一个提交按钮。
JavaScript 代码如下
jsconst form = document.querySelector("#userinfo");
async function sendData() {
// Associate the FormData object with the form element
const formData = new FormData(form);
try {
const response = await fetch("https://example.org/post", {
method: "POST",
// Set the FormData instance as the request body
body: formData,
});
console.log(await response.json());
} catch (e) {
console.error(e);
}
}
// Take over form submission
form.addEventListener("submit", (event) => {
event.preventDefault();
sendData();
});
我们为表单元素添加了一个提交事件处理程序。它首先调用 preventDefault() 来阻止浏览器内置的表单提交,以便我们接管。然后我们调用 sendData(),它会检索表单元素并将其传递给 FormData 构造函数。
之后,我们使用 fetch() 将 FormData 实例作为 HTTP POST 请求发送。