使用Fetch API阻止重定向,实现纯HTML+JS表单提交至服务器
Solution: Submit Form with Fetch API & Prevent Redirect
Got it, let's get this sorted for you! Here's how to modify your form to use the Fetch API and stop the default page redirect when submitting:
Full Working Code Example
<form id="email-signup" action="http://www.server.com" method="post"> <input id="firstname-input" type="hidden" name="firstname" value=""> <input type="text" name="email" placeholder="Input Email" required> <!-- Added basic client-side validation --> <input type="hidden" name="campaign[id]" value="1"> <input type="hidden" name="campaign[name]" value="Text Campaign"> <input type="submit" value="Submit"> </form> <script> // Grab the form element from the DOM const signupForm = document.getElementById('email-signup'); // Attach a submit event listener signupForm.addEventListener('submit', async (event) => { // Critical: Stop the browser's default form submission (which causes redirect) event.preventDefault(); try { // Automatically collect all form data (including hidden fields) const formData = new FormData(signupForm); // Send the request via Fetch API const response = await fetch(signupForm.action, { method: signupForm.method, body: formData, // Uncomment below if your server expects url-encoded data instead of multipart // body: new URLSearchParams(formData), }); // Handle successful submission if (response.ok) { const responseData = await response.text(); // Use response.json() if server returns JSON console.log('Signup succeeded:', responseData); // Optional: Reset the form and show user feedback signupForm.reset(); alert('Thanks for signing up!'); } else { console.error('Signup failed:', response.statusText); alert('Oops, something went wrong. Please try again.'); } } catch (error) { console.error('Network error:', error); alert('Could not connect to the server. Check your internet connection.'); } }); </script>
Key Details Breakdown
- Prevent Redirect: The
event.preventDefault()line is what stops the browser from reloading/redirecting when you hit submit—this is the core of what you asked for. - FormData Convenience: Using
FormDatameans you don't have to manually collect each input's value; it grabs every field (including hidden ones) from your form automatically. - Async/Await: Makes the asynchronous Fetch code easier to read and manage compared to nested promise chains.
- Error Handling: Covers both network failures and non-success HTTP status codes (like 404 or 500) so you can give users meaningful feedback.
Quick Notes
- If your server expects data in
application/x-www-form-urlencodedformat instead of the defaultmultipart/form-data, replacebody: formDatawithbody: new URLSearchParams(formData). - If your frontend is hosted on a different domain than
http://www.server.com, make sure the server is configured to allow CORS—otherwise you'll get a cross-origin error.
内容的提问来源于stack exchange,提问作者Adith Widya Pradipta
相关产品推荐
相关产品推荐

