Problems with history.js back button

2019-08-12 05:12发布

I'm using history.js to update my site, which works great. It is a PHP based webshop, that, if it detects an ajax request, only serves JSON with the main div's data:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) 
    && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {}

On load, I ajaxify my links, an approach taken from history.js' github: https://github.com/browserstate/History.js/

function ajaxify() {
var History = window.History;
$('a[rel="ajax"]').click(function(e){
    if(History.enabled) {
        e.preventDefault();
        var url = $(this).attr("href");
        var options = {};
        History.pushState(null, 'Shop', url);
    }
    else {
        window.location.replace(url);
    }
});
}

Heres the event handler:

History.Adapter.bind(window,'statechange',function(){
    var State = History.getState();
    var returnLocation = history.location || document.location;
    var url = returnLocation.pathname;
    var options = searchString(returnLocation.search);
    shopUpdate(url,options)
});

And this is the ajax call:

function shopUpdate(url,options) {
     $.ajax({
        url: url,
        type: "GET",
        dataType:'json',
        data: options,
        success: function(data, textStatus, jqXHR){
            $('#shop').html(data.page);
            ajaxify();  
        }
    });
}

There's on scenario that breaks everything: Some links aren't "ajaxified" and when I click a couple of ajax links, then a "regular" one, and then "back" I get the raw JSON output. The Url is right and when I reload, I get the page I want. It's like PHP thinks it's Ajax and serves JSON but History statechange doesn't fire since I got there via a regular link. I'm quite confused and appreciate any help!

Thanks, thomas

1条回答
孤傲高冷的网名
2楼-- · 2019-08-12 05:49

It turned out this was a problem with Chrome, the back button and the cache. I added Cache-Control: no-store to the JSON Header and now it works.

查看更多
登录 后发表回答