You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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—URLSearchParams handles parameter encoding and parsing reliably.
  • Scalable: If you add more filter checkboxes (brand, category), just call updateUrlParameter with the new parameter name and value, and everything else stays intact.
  • Fixes a Small Bug: Corrected the typo cash: false to cache: false to ensure your AJAX requests aren't cached by the browser.

内容的提问来源于stack exchange,提问作者Salar Bahador

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:45:16