PHP网站中点击页面链接时如何终止所有jQuery $.post请求?
Hey there! Let's fix that frustrating issue where your page hangs waiting for unfinished AJAX requests to complete before navigating. Since your jQuery code lives in an external script used across all pages, we don't need to track individual request variables—we can handle this cleanly with a global solution.
Solution: Track & Abort All Active AJAX Requests Globally
We'll leverage jQuery's global AJAX events to maintain a running list of in-flight requests, then abort them all the moment a user triggers a page navigation.
Step 1: Add Global Request Tracking to Your External Script
Update your /scripts/js.js file with this code to automatically log and clean up active requests:
// Global array to store all active AJAX request instances let activeAjaxRequests = []; // Capture every outgoing AJAX request (including $.post calls) $(document).ajaxSend(function(_, jqXHR) { activeAjaxRequests.push(jqXHR); }); // Remove requests from the list once they finish (success or failure) $(document).ajaxComplete(function(_, jqXHR) { const requestIndex = activeAjaxRequests.indexOf(jqXHR); if (requestIndex !== -1) { activeAjaxRequests.splice(requestIndex, 1); } });
Step 2: Intercept Navigation to Kill Pending Requests
Add this code to intercept link clicks (and other navigation triggers) so we abort requests before letting the page navigate:
// Intercept all link clicks to abort requests first $(document).on('click', 'a', function(e) { // Abort every active AJAX request in the list activeAjaxRequests.forEach(request => request.abort()); // Clear the list to avoid leftover references activeAjaxRequests = []; // Let the navigation proceed normally const targetHref = $(this).attr('href'); if (targetHref && targetHref !== '#') { window.location.href = targetHref; return false; } }); // Optional: Handle form submissions too (if your site uses them) $(document).on('submit', 'form', function() { activeAjaxRequests.forEach(request => request.abort()); activeAjaxRequests = []; });
Bonus: Add a Global Timeout (Fallback)
As an extra safety net, you can set a global timeout for all AJAX requests so they don't hang indefinitely even if navigation isn't intercepted:
// Set a 1-second timeout for all AJAX requests (adjust duration as needed) $.ajaxSetup({ timeout: 1000 });
Why This Works for Your Setup
- No changes needed to your existing
loadExternalData()function—we don't have to manually track individual requests - It works across all pages since it's in your global external script
- Covers all AJAX requests, not just the ones from your username-loading function
内容的提问来源于stack exchange,提问作者Toby Twigger

