history.pushState() and clicking back/forward butt

2019-08-25 03:19发布

This is my code to change url on ajax load which works

$.ajax({
  url: url,
  success: function (data) {
  $(selector).html(data);
    var title = data.match("<title>(.*?)</title>")[1]; // get title of loaded content   
    window.history.pushState( {page : 0} , document.title, window.location.href ); // store current url.    
    window.history.pushState( {page : 1} , title, url ); // Change url.
    document.title = title; // Since title is not changing with window.history.pushState(), 
    //manually change title. Possible bug with browsers.
    window.onpopstate = function (e) {
        window.history.go(0);
    };
  }
});

when i click back , previous page is loading. And if i click again nothing happen. And one more click it will goto first page. After some testing i found , there are 2 same page in back button ,on each ajax loading

enter image description here

Also i need a code to get history when click forward button

1条回答
相关推荐>>
2楼-- · 2019-08-25 04:04

Moderators have removed my post, for the reason that I really given little scraps of code to try to help.


But still I will try to give an example:

Suppose you have this code is triggered by the event onclick.

$(function() {
    function load(url, push) {
        $.ajax({
            url: url,
            success: function (data) {
                var title = data.match("<title>(.*?)</title>")[1];
                document.title = title;
                if (push) {
                    history.pushState(null, title, url);
                }
            }
        });
    }

    $(document).click(function(e) {
        if (e.target.nodeName === 'A') {
            var url = $(e.target).attr('href');
            if (url.indexOf('#') !== 0) {
                load(url, true);
                e.preventDefault();
            }
        }
    });

    $(window).bind('popstate', function(e) {
        load(window.location.href, false);
    });
});
查看更多
登录 后发表回答