在 HTML 中,可以使用 <form>
标签来创建表单,并使用 <input>
标签来创建表单元素。为了将表单数据传递给服务器,可以使用 FormData
对象。
以下是一个使用 FormData
对象的示例:
<form id="myForm">
<input type="text" name="username">
<input type="email" name="email">
<button type="button" onclick="submitForm()">Submit</button>
</form>
<script>
function submitForm() {
const form = document.getElementById('myForm');
const formData = new FormData(form);
fetch('/submit', {
method: 'POST',
body: formData
})
.then(response => {
console.log('Success:', response);
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
在示例中,我们首先获取了表单元素,并使用它创建了一个 FormData
对象。然后,我们使用 fetch
函数将数据发送到服务器。
值得注意的是,我们将 FormData
对象作为 fetch
函数的 body
参数传递。这将确保表单数据以正确的格式发送到服务器。
在这个例子中,我们使用了 fetch
函数来发送请求。fetch
是一个现代的网络请求 API,可以在现代浏览器中使用。如果需要兼容旧版浏览器,可以使用 XMLHttpRequest 或其他网络请求库来实现相同的功能。