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

如何实现不刷新页面修改URL并获取参数值?

Solution to Update URL Without Page Refresh & Fetch Parameter Values

Alright, let's get your code working to update the URL without a page refresh and fetch the corresponding parameter value properly. Here's how to tweak your existing code step by step:

Step 1: Update the Frontend (index.php)

Your original JavaScript was incomplete—we need to finish the history.pushState call, add an AJAX request to fetch the parameter value dynamically, and handle browser history navigation (back/forward buttons). Here's the revised code:

<?php foreach($heading as $sub) {
    $cleanLink = str_replace(" ",'-',$sub);
    // Use a data attribute to store the link value (more reliable than relying on IDs)
    echo "<li> <a href='javascript:void(0)' class='links' id='{$cleanLink}' data-link='{$cleanLink}'> <i class='fa fa-angle-double-right'></i>&nbsp;{$sub} </a> </li>";
} ?>

<!-- Add a container to display the current parameter value (optional but helpful) -->
<div id="current-link-display">No link selected yet</div>

<script>
$(document).ready(function(){
    $(".links").click(function(){
        // Grab the link value from the data attribute
        const selectedLink = $(this).data('link');
        // Build the full URL with your base URL and the link parameter
        const baseUrl = '<?php echo base_url("welcome/tutorial_overview"); ?>';
        const updatedUrl = `${baseUrl}?link=${selectedLink}`;

        // Update the URL in the address bar without reloading the page
        // We pass the link value in the state object to use later for history navigation
        history.pushState({ activeLink: selectedLink }, '', updatedUrl);

        // Fetch the parameter value from your backend using AJAX
        $.ajax({
            url: updatedUrl,
            type: 'GET',
            success: function(response) {
                // Update the page content with the retrieved value
                $('#current-link-display').text(`Selected Link Parameter: ${response}`);
                // If you need to do something else with the value, add it here
            },
            error: function(xhr) {
                console.error('Oops, there was an error fetching the data:', xhr);
            }
        });
    });

    // Handle browser back/forward buttons to keep content in sync with URL
    window.addEventListener('popstate', function(event) {
        if (event.state && event.state.activeLink) {
            const baseUrl = '<?php echo base_url("welcome/tutorial_overview"); ?>';
            const restoredUrl = `${baseUrl}?link=${event.state.activeLink}`;
            
            // Fetch the data again to update the page
            $.ajax({
                url: restoredUrl,
                type: 'GET',
                success: function(response) {
                    $('#current-link-display').text(`Selected Link Parameter: ${response}`);
                }
            });
        }
    });
});
</script>

Frontend Tweaks Explained:

  • Added a data-link attribute to store the link value (cleaner than using IDs for data storage)
  • Completed the base_url call to generate a valid URL with the link parameter
  • Used history.pushState to update the URL without a refresh, and stored the link value in the state object
  • Added an AJAX request to fetch the parameter value from your controller dynamically
  • Added a popstate listener to handle browser history navigation, ensuring the page content matches the URL when the user clicks back/forward

Step 2: Adjust the Backend Controller (Welcome.php)

Your original controller code works, but let's add a safety check to avoid "Undefined index" errors if the link parameter is missing. We'll also keep the output clean for AJAX to handle:

public function tutorial_overview() {
    // Check if the link parameter exists; use a default if not
    $link = isset($_GET['link']) ? $_GET['link'] : 'default-link';
    // Echo the value directly (AJAX will receive this as plain text)
    echo $link;
    // If you prefer JSON output (for more complex data), use this instead:
    // echo json_encode(['selected_link' => $link]);
    // Then parse it in the AJAX success callback with JSON.parse(response)
}

Backend Tweaks Explained:

  • Added isset() check to handle cases where the link parameter isn't present
  • Kept the output simple so AJAX can easily consume it

Step 3: Test It Out

  1. Make sure your base_url is correctly configured in your CodeIgniter settings
  2. Click any of the links in your list—you'll see the URL update in the address bar, and the current-link-display div will show the selected parameter value without a page refresh
  3. Try using the browser's back/forward buttons— the content should update to match the URL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:30:07