Implementing “Back button” on jquery ajax calls

2019-07-29 13:13发布

问题:

I'm trying to implement back button on this full ajax website.. I tried jquery history plugin but I'm sure I messed something, as the hash appears OK but the back button won't load the original content back..

This is what my menu looks like:

       <div id="nav" class="ajaxload menu">
            <ul>
                <li><a href="home.aspx">Home</a></li>
                <li><a href="about.aspx">About Us</a></li>
                <li><a href="contact.aspx">Contact</a></li>
            </ul>
        </div>    

And the ajax calls:

     $(function() {
            var $content = $('#content');
            $('.ajaxload li a').click(function() {

                $content.html('<div id="loader"></div>');

                var url = $(this).attr('href');
                $.get(url, function(data) {
                    $content.hide().html(data).fadeIn("slow", function() { $("#loader").fadeOut("fast") });
                });
                return false;
            });
        });

回答1:

I'm guessing that when you were using the history plugin you may not have initialized it. When you initialize it, you pass it a callback that handles the hash changes so you can load the content again. So, for example, rather than doing something like this:

$('a').click(function clickedLink() {
    var href=$(this).attr('href');
    $.history.load(href);
    doSomeAJAXRequest(href);
    return false;
});

You'd have to do something like this:

$.history.init(function hashChanged(hash) {
    doSomeAJAXRequest(href);
});
$('a').click(function clickedLink() {
    var href=$(this).attr('href');
    $.history.load(href);
    return false;
});