XMLHttpRequest始终以GET发送,自制AJAX JS库失效求助
Hey there! Let’s break down why your AJAX request works on the first click but dies on the second. Based on the code snippet you shared, here are the most likely issues and fixes you can try right away:
1. You’re Not Preventing the Form’s Default Submit Behavior
If your login button is inside a <form> tag, clicking it will trigger the browser’s default form submission—this refreshes the page, which can interrupt or override your AJAX request after the first click. Even if the first request goes through, the page refresh resets your state, making the second click behave unpredictably.
Fix this by adding event.preventDefault() at the start of your click handler:
$loginBtn.on("click", function(event) { // Stop the browser from reloading the page event.preventDefault(); if(validateForm($loginForm)) { var xhttp = new XMLHttpRequest(); xhttp.open("POST", "your-endpoint-url", true); // Keep async = true // ... rest of your AJAX setup } });
2. Incomplete AJAX State Handling
It’s easy to skip error handling or forget to properly check the request’s ready state. If your onreadystatechange callback only handles successful responses (status 200) and ignores errors or incomplete states, subsequent requests might get stuck or fail silently.
Make sure your callback covers all cases:
xhttp.onreadystatechange = function() { if (this.readyState === 4) { // Request is complete if (this.status === 200) { // Handle successful response console.log("Login successful:", this.responseText); } else { // Handle errors (404, 500, etc.) console.error("Login failed. Status code:", this.status); } } }; // Don't forget to set the correct Content-Type for POST requests xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Send your form data (encode it to avoid issues!) xhttp.send("username=" + encodeURIComponent($loginForm.querySelector("#username").value) + "&password=" + encodeURIComponent($loginForm.querySelector("#password").value));
3. Accidental Event Re-Binding
If your code runs the $loginBtn.on("click", ...) line multiple times (e.g., inside a loop or a function that gets called repeatedly), you’ll end up with multiple click handlers attached to the button. Each click will fire all handlers, causing conflicting AJAX requests that fail on subsequent attempts.
Fix this by unbinding existing handlers before adding a new one:
// Clear any existing click handlers first $loginBtn.off("click").on("click", function(event) { event.preventDefault(); if(validateForm($loginForm)) { // ... your AJAX logic } });
4. Browser Caching (Uncommon for POST, But Possible)
While POST requests are rarely cached, some browsers or server configurations might still cache responses. Add a unique timestamp to your request URL to bypass this:
// Append a timestamp to avoid caching var requestUrl = "your-endpoint-url?t=" + new Date().getTime(); xhttp.open("POST", requestUrl, true);
Start with checking the first two issues—they’re the most common culprits for this exact problem. Once you’ve implemented those fixes, test your login flow again and see if the second request works as expected.
内容的提问来源于stack exchange,提问作者NoobishPro

