如何根据后端返回值重复AJAX请求直至满足指定条件?
Hey Jonas, let's fix this up for you! The core idea here is wrapping your AJAX call in a reusable function so we can easily repeat it when the backend returns 2. We'll also add a small delay between retries to avoid overwhelming your server.
Step 1: Refactor AJAX into a reusable polling function
First, let's pull the AJAX logic into its own function—this makes it simple to call again whenever we need to check the backend status:
$(document).ready(function() { // Define the reusable function to check match status function checkMatchStatus() { $.ajax({ url: 'includes/matchmaking.php', success: function(data) { // Convert response to a number (backend might return text like "1" or "2") const status = parseInt(data.trim(), 10); if (status === 1) { // Execute your desired action when status is 1 alert("Match successful!"); // Add your custom logic here (e.g., update UI, redirect user) } else if (status === 2) { // If status is 2, wait 1 second and poll again setTimeout(checkMatchStatus, 1000); // Optional: Add UI feedback for users // $(".waiting-status").text("Looking for a match..."); } else { // Handle unexpected response values alert("Unexpected server response: " + data); } }, error: function(xhr, status, error) { // Catch failed requests to avoid infinite loops alert("Request failed: " + error); // Optional: Retry on error with a longer delay // setTimeout(checkMatchStatus, 3000); } }); } // Trigger the polling when the .match button is clicked $(".match").click(function() { checkMatchStatus(); }); });
Step 2: Key Details Explained
- Reusable Function:
checkMatchStatus()handles both the AJAX request and decision logic, making it easy to repeat the poll when needed. - Type Conversion:
parseInt(data.trim(), 10)ensures we're comparing numbers instead of strings—critical because your backend might return text like"1"instead of a numeric value. - Controlled Retries:
setTimeout(checkMatchStatus, 1000)adds a 1-second delay between retries. Adjust this value based on how quickly you expect the backend to update (don't make it too short to avoid server overload). - Error Handling: The
errorcallback catches network issues or server errors, preventing the code from getting stuck in an infinite loop of failed requests. - Optional UI Feedback: You can add code to update the page (like a loading spinner or status message) so users know the system is working while waiting.
Step 3: Backend PHP Tips
Make sure your matchmaking.php returns only the numeric value (1 or 2) with no extra whitespace or HTML—even a single space can break the parseInt conversion. Example PHP code:
// In matchmaking.php // Calculate your status value based on your logic $status = 1; // or 2 // Output only the number, no extra content echo $status; exit;
That's all! This setup will trigger the initial AJAX call when the button is clicked, and keep polling the backend until it returns 1.
内容的提问来源于stack exchange,提问作者Jonas Tamoševičius

