使用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>