简体   繁体   中英

Using AJAX to navigate between pages

I've implemented a JS solution to navigate between pages but now, I realize that's not enought for my needs.

I'd like to navigate between pages using AJAX, and my first idea was this one:

$(document).ready(function() {
    //initial
    $('#main').load('content/index.php');

    //M. clicks
    $('.menu_pc li a').click(function(){
        var page = $(this).attr('href');
        $('#main').load('content/' + page + '.php');
        return false;
    });
});

Where #main it's the ID of the HTML section.

What happen if I use this method? Well, that I'm kind of limited because I should handle every click using the same method and I'm not sure if it will even work or not (first time using this).

For instance, if I have to recharge the header after some login from a user showing him his own name, I probably have problems using that method. That's why I need to use some REAL AJAX code.

Like replace this form for a welcome message like "Hello user ".

在此处输入图片说明

Some hint?

Thanks in advance.

You can use this method. But it depends on what is your purpose? If you want to create very simple website with several pages it will be ok.

But if you plan to create something bigger, it will be hardly scalable if you will do it that way.

So if your purpose is to create a big and easily scalable website, then consider using for example angular or emberjs.

You could just use

$(document).ready(function() {
  //initial
  $('#main').load('content/index.php');

  //M. clicks
  $('.menu_pc li a').click(function(){
    var page = $(this).attr('href');
    var redirectUrlPath = 'content/' + page;
    window.location.pathname = redirectUrlPath;
    return false;
  });
});

I'm not sure exactly what you want, but this will redirect you to a different page. Assuming your A tag looks something like this:

<a href='myNewPage'>link1</a>

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