简体   繁体   中英

How to change url and get value without refreshing page?

controller: Welcome.php

public function tutorial_overview()
{
    $link = $_GET['link'];
    echo $link;
}

view: index.php

<?php
    foreach($heading as $sub)
    {
    echo "<li>
            <a href='javascript:void(0)' class='links' id='".str_replace(" ",'-',$sub)."'>
                <i class='fa fa-angle-double-right'></i>&nbsp;".$sub."
            </a>
        </li>";
    }
?>

<script>
    $(document).ready(function(){
        $(".links").click(function(){
            link = this.id;
            history.pushState(null, null, '<?php echo base_url(); ?>'+link);
            $.ajax({
                type:"GET",
                url:"<?php echo base_url(); ?>tutorial_overview/"+link,
                success:function(data){
                    alert(data);
                }
            });
        });
    });
</script>

In this code I have create a view file inside it I have define

<a href='javascript:void(0)' class='links' id='".str_replace(" ",'-',$sub)."'>
            <i class='fa fa-angle-double-right'></i>&nbsp;".$sub."
        </a>

which is dynamic. Now I want to change the url link as well as change the content that means when I click on link url will change and content will also change without refreshing page. So, How can I do this ?Please help me.

Thank You

I think your jQuery code has the problem -

link = this.id;

Try to apply code below -

$(".links").click(function(){
    var link = $(this).attr('id');
    var newUrl = '<?php echo base_url(); ?>' + link;

    history.pushState({}, null, newUrl);

    $.ajax({
        type:"GET",
        url:"<?php echo base_url(); ?>tutorial_overview/"+link,
        data: { link: link },
        success:function(data){
            alert(data);
        }
    });
});

What you need to do is - Call ajax, get data and then do other stuff. You may change URL via history pushState when need. Be aware that older browser isn't compatible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM