首页 > 解决方案 > AJAXified Wordpress主题中的历史replaceState问题

问题描述

我制作了一个支持 Ajax 的 Wordpress 主题,其主要功能是内部链接不会重新加载整个页面,而只会重新加载新内容。因此,当 URL 的哈希值发生变化时,新内容将放在 #primary 部分中,而后台的地图保持不变:

var $mainContent = $("#primary")

$(window).bind('hashchange', function(){
    url = window.location.hash.substring(1);

    url = url + " #content"; 

    $mainContent.animate({opacity: "0.1"}).html('<p>Please wait...</>').load(url, function() {
        $mainContent.animate({opacity: "1"});
    });
});

一切正常,历史向后和向前导航。您可以在此处查看基本功能。

现在我想要隐藏哈希的漂亮 URL,例如像http://geraldkogler.com/places/#/places/place/stwst/这样的链接被更改为http://geraldkogler.com/places/place/stwst/ . 我这样做将此代码添加到ajax.js的第 47 行:

var oPageInfo = {
    title: "places",
    url: window.location.origin+window.location.hash.substring(1)
}   
window.history.replaceState(oPageInfo, oPageInfo.title, oPageInfo.url);

现在 URL 被重写了——但历史不再起作用了。

所以我认为我应该听 popstate 事件,我尝试执行以下操作,因此返回一次,但不会更多:

window.onpopstate = function(event) {
    if (event.state) {
        var host = "http://"+location.hostname;
        location.hash = event.state.url.substring(host.length);
    }
};

此页面上显示了上述代码的这种(错误)行为。知道我在ajax.js中做错了什么吗?

标签: javascriptajaxwordpresshtml5-history

解决方案


推荐阅读