AJAX Form Submission: A Complete Guide with Code Example
const form = document.querySelector('#myForm');
const submitBtn = document.querySelector('#submitBtn');
submitBtn.addEventListener('click', (e) => {
e.preventDefault(); // 阻止表单默认提交行为
const formData = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/submit-form');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
alert('Form submitted successfully!');
} else {
alert('Form submission failed.');
}
}
};
xhr.send(formData);
});
This code demonstrates a basic AJAX form submission using JavaScript. It listens for the submit button click, prevents the default form submission behavior, gathers data using the FormData object, and sends a POST request using XMLHttpRequest. The code then handles the response, displaying a success or error message based on the server's response. This approach offers a more dynamic and user-friendly experience compared to traditional form submissions.
原文地址: http://www.cveoy.top/t/topic/gl8T 著作权归作者所有。请勿转载和采集!