简体   繁体   中英

Ajax / HTML5 history states (popState, pushState, etc) - back button behavior

There have been several questions about the pushState functionality of HTML5, but I'm not able to find anything about two issues I'm having. My popstate handler is defined like so:

$(window).bind('popstate', function (e) {
    if (!e.originalEvent.state)
        return;

    LoadContent({ url: e.originalEvent.state.path });
}

The LoadContent call simply fills a content pane using ajax.

Problem 1: Lets imagine that we start off at page1 of my site by browsing to it. LoadContent won't be called since there is no state . Let's imagine that my browsing history is like so:

page1 -> (ajax)page2 -> (ajax)page3 -> (back pressed)page2 -> (back pressed)page1

When I press the browser's back button to go to page2 , everything is fine. However, when I press back again, which should load the content for page1 , e.originalEvent.state is null , meaning LoadContent won't be called and so the content will remain the same as on page2 . How can I get page1 's content to load when pressing back?

Problem 2: Imagine we press back from page3 to page2 , which means we load the 2nd page's content through ajax. Now imagine, we browse (ie, put in the URL manually into the browser's address bar) to page3 again, and then press back again to go to page2 . Instead of showing the 2nd page, the browser will instead show just the ajax results of page2 's content that we retrieved earlier, so that the rest of the page is not loaded. How can this be fixed?

Thanks for any help!

For your problem 1:

You need to either reload the entire page or load it back via ajax, because the data in the initial page will not be pushed to the history. Or else you could change your page load event to load the data from ajax and load the contents dynamically, then you will have the necessary json data that needs to be pushed to the history.

I just had the same issue as your Problem 2 .

You can send HTTP headers to prevent the web browser from caching and displaying the XHR content. Do this on the page that executes your History object JS.

In PHP:

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

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