Laravel分页商品页:如何动态生成带筛选与页码的URL
Solution: Preserve Page Number When Filtering with AJAX & pushState
Absolutely! You can dynamically modify your URL parameters while keeping the current page number and other existing filters—no more manual URL splicing that loses state. Here's a clean, maintainable approach using jQuery and modern URL APIs:
Step 1: Add a Helper Function to Manage URL Parameters
First, create a reusable function to update specific URL parameters without wiping out existing ones. This handles all the parsing and rebuilding work for you:
// Helper to safely update URL parameters while preserving existing values function updateUrlParameter(url, paramName, paramValue) { const urlParts = url.split('?'); const baseUrl = urlParts[0]; const queryString = urlParts.length > 1 ? urlParts[1] : ''; const params = new URLSearchParams(queryString); // Update or remove the parameter (remove if value is empty/null) if (paramValue !== null && paramValue !== '') { params.set(paramName, paramValue); } else { params.delete(paramName); } // Rebuild the full URL const newQuery = params.toString(); return newQuery ? `${baseUrl}?${newQuery}` : baseUrl; }
Step 2: Modify Your AJAX Click Handler
Update your existing click event to use this helper, so it retains the current page number and any other active filters:
$(document).on('click', "#only_available", function () { // Determine the selected status value const status = $(this).is(':checked') ? 1 : 0; // Get the current full URL (includes page and any other filters) const currentUrl = window.location.href; // Update the 'status' parameter while keeping all existing ones (like page) const newUrl = updateUrlParameter(currentUrl, 'status', status); // Update browser history without reloading the page window.history.pushState("", "", newUrl); // Extract all parameters from the updated URL to send in the AJAX request const requestParams = new URLSearchParams(newUrl.split('?')[1] || ''); $.ajax({ url: '/Collections/Newest_Items', type: "GET", data: requestParams, // Send ALL current parameters (status + page + others) cache: false, // Fixed typo from your original code: 'cash' → 'cache' success: function (response) { $('#products-load').html(response); } }); });
Key Benefits of This Approach:
- Preserves All State: Keeps the current page number, plus any other existing filter parameters (like brand or category) you might add later.
- Clean & Maintainable: No messy manual string concatenation—
URLSearchParamshandles parameter encoding and parsing reliably. - Scalable: If you add more filter checkboxes (brand, category), just call
updateUrlParameterwith the new parameter name and value, and everything else stays intact. - Fixes a Small Bug: Corrected the typo
cash: falsetocache: falseto ensure your AJAX requests aren't cached by the browser.
内容的提问来源于stack exchange,提问作者Salar Bahador
相关产品推荐
相关产品推荐

