如果有斜杠,则History.pushState(data,title,url)将url连接(而不是替换)url到地址栏

Fra*_*art 8 history.js

例如,

如果我使用"www.site.com"的搜索栏,我会看到"www.site.com/search",这很好.

如果我使用"www.site.com/events/"中的搜索栏,我会看到"www.site.com/events/search",这很愚蠢.

为什么这样做?这是行为还是history.js错误或我的错误?

小智 13

举一个你正在做的事情的例子.

如果您在地址栏中的当前URL具有以下形式:http://somesite.com/path/ 并且您传递pushState( null, null, 'newpath' );了这种情况,链接将如下所示,http://somesite.com/path/newpath但如果您将参数传递为:pushState( null, null, '/newpath' ),在这种情况下将如下所示: http://somesite.com/newpath


Sim*_*ver 5

如果您的应用程序没有部署在根目录(例如使用虚拟目录,或者只是在更深的层次结构中),那么您最终会搞砸 URLhistory.pushState({}, '/newpath');

有几种选择:

1) 在 JavaScript 变量中获取根路径,您可以在其前面添加 URL。在这个例子中window.ViewModel.rootPath只是一个任意的地方 - 只需修改它即可存储全局变量。

您必须设置rootPathin 脚本(此处为 .NET 的示例)。

<script>
    window.ViewModel.rootPath = "@Request.ApplicationPath";
</script>

history.pushState({}, window.ViewModel.rootPath + '/newpath');
Run Code Online (Sandbox Code Playgroud)

2) 检查 URL 是否以 a 结尾/,如果是,则需要上一级目录。注意:此方法要求您知道您要发布的内容的“父”目录 - 在本例中是YourAccount

history.pushState({ mode: 'Club' }, '',
     (window.location.href.endsWith('/') ? '../' : '') +
      'YourAccount/ManageClub/' + id );
Run Code Online (Sandbox Code Playgroud)

如果当前 URL 是,/preview/store/YourAccount则这将变为../YourAccount/ManageClub/123

如果当前 URL 是,/preview/store/YourAccount/则这将变为YourAccount/ManageClub/123

它们都以相同的 URL 结束。