使用history.pushState()时更新整个location.pathName

Update entire location.pathName when using history.pushState()

本文关键字:location pathName 更新 history pushState 使用      更新时间:2023-09-26

我正在创建一个网站,将我的所有内容加载到我的主index.php中。我正在努力让它使用干净的URLS。

示例:http://www.host.com/home

这个URL会将home.php加载到index.php中。我正在使用history.pushstate()更新我的历史记录,但在某些页面上,我希望有一个更深入的URL。

示例:http://www.host.com/forum/topicName

这将把论坛页面加载到索引中,并从mySQL中获取主题名称并显示它。但从这里开始,如果我单击导航按钮,URL将显示为这样。。。

示例:http://www.host.com/forum/home

我想让它清除那个/论坛,然后离开/主页。到目前为止,这里是我的一些代码。

function myNav(whereTo)
{   
    window.history.pushState(null, null, whereTo);
    var toLoad = 'pages/'+whereTo+'.php';
    $('#mainContent').load(toLoad);
}

这就是我现在使用的快速解决方案,我希望有更好的方法。

if(window.location.pathname.lastIndexOf('/') != 0)
        window.location.pathname = whereTo;
    else
        window.history.pushState(null, null, whereTo);

谢谢你。我想在中的URL开头添加一个/

window.history.replaceState(stateObj, title, URL);

将整个pathName替换为opposedin,与我的做法相反,只是添加页面名称。