使用JavaScript提交表单可以通过以下步骤实现:
document.getElementById()
或document.querySelector()
等方法获取表单元素。var form = document.getElementById("myForm");
addEventListener()
方法监听表单的submit
事件。form.addEventListener("submit", function(event) {
event.preventDefault(); // 阻止表单的默认提交行为
// 在这里执行表单提交的逻辑
});
elements
属性获取所有表单字段,然后通过字段的name
属性获取字段名,通过value
属性获取字段值。var formData = new FormData(form);
var data = {};
for (var pair of formData.entries()) {
data[pair[0]] = pair[1];
}
XMLHttpRequest
对象或fetch
API发送表单数据到服务器。var xhr = new XMLHttpRequest();
xhr.open("POST", "submit-url", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// 请求成功处理逻辑
}
};
xhr.send(JSON.stringify(data));
完整代码示例:
<form id="myForm">
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<button type="submit">提交</button>
</form>
<script>
var form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault();
var formData = new FormData(form);
var data = {};
for (var pair of formData.entries()) {
data[pair[0]] = pair[1];
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "submit-url", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// 请求成功处理逻辑
}
};
xhr.send(JSON.stringify(data));
});
</script>