Home > Article > Web Front-end > What are the methods for JS form submission?
There are several common ways to submit JS forms: using the submit() method of the form element, using AJAX for asynchronous submission, and using the fetch API for asynchronous submission.
Code example:
<form id="myForm" action="submit.php" method="POST"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="提交" /> </form> <script> const form = document.querySelector('#myForm'); form.addEventListener('submit', (e) => { e.preventDefault(); // 阻止表单的默认提交行为 // 进行表单验证 // ... // 提交表单 form.submit(); }); </script>
Code Example - Using native XMLHttpRequest:
<form id="myForm" action="submit.php" method="POST"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="提交" /> </form> <script> const form = document.querySelector('#myForm'); form.addEventListener('submit', (e) => { e.preventDefault(); // 阻止表单的默认提交行为 // 进行表单验证 // ... // 构造请求对象 const xhr = new XMLHttpRequest(); xhr.open('POST', 'submit.php', true); // 设置请求头 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 监听请求状态 xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.responseText); } }; // 发送请求 xhr.send(new FormData(form)); }); </script>
Code example:
<form id="myForm" action="submit.php" method="POST"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="提交" /> </form> <script> const form = document.querySelector('#myForm'); form.addEventListener('submit', (e) => { e.preventDefault(); // 阻止表单的默认提交行为 // 进行表单验证 // ... // 构造请求参数对象 const formData = new FormData(form); // 发起fetch请求 fetch('submit.php', { method: 'POST', body: formData }) .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.log(error)); }); </script>
The above are common form submission methods in JS. You can choose the appropriate method for form submission according to actual needs.
The above is the detailed content of What are the methods for JS form submission?. For more information, please follow other related articles on the PHP Chinese website!