简体   繁体   中英

How do I relocate the user to contents of another page without page refresh when navigating?

Im using javascript - ajax and jquery to load all contents from php files which is under (#menu a)[see below 'you.php'] without refreshing the page when navigating across the page - which works perfectly.

However, how do I create a hyperlink of somesort on content-A (which loads and shows all the contents from home.php) when clicked, it relocates & shows the user to/the contents of settings.php(B).

Please note my href hyperlinks doesn't have .php at the end. The 'general.js' file explains why.

(you.php):

        <div id="menu">

            <a href="home">Home</a>

            <a href="settings">Settings</a> // Content (A)

        </div>

        <div id="content"><div>

        <script src="./js/jquery-2.1.4.min.js"></script>

        <script src="./js/general.js"></script>

(general.js):

$(document).ready(function() {

// initial content that will be loaded first upon logging in:

$('#content').load('home.php');

// handle menu clicks

$('#menu a').click(function(){

    var page = $(this).attr('href');

    $('#content').load(''  + page +  '.php');

    return false;

    });

});

(home.php):

 <h1> welcome to homepage </h1>

 Would you like to go to your settings?

 Click here: <a href="settings.php>Settings</a> 

Obviously the problem with doing the href hyperlink like this in home.php, is that it goes directly to the settings.php page. Which makes my general.js (ajax) and jquery file pointless. Since the whole point of using ajax and jquery is for smooth navigation and no page refresh upon navigating around the website.

and No, I do not want to load the contents of settings.php within the contents of home.php, 'loadception' is not what I'm looking for.

This is my simple question, I would like a simple answer in php,javascript,ajax.

Any ideas?

You need to use event delegation. To better performance in my example, all links that must be loaded into "#content" have a class "open" so, in jquery you could do some like this:

$('#content').on('click', '.open', function(e) {
    e.preventDefault();

    var page = $(this).attr('href');
    $('#content').load(''  + page +  '.php'); // concat .php if it's only necessary
});

Updated I created a demo on github: https://github.com/josemato/stackoverflow/tree/master/spa-event-delegation

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