重定向到JavaScript中的相对URL

use*_*337 328 javascript url redirect

我有一个问题:我想通过JavaScript重定向到上面的目录.我的代码:

location.href = (location.href).substr(0, (location.href).lastIndexOf('folder'));
Run Code Online (Sandbox Code Playgroud)

网址如下所示:

example.com/path/folder/index.php?file=abc&test=123&lol=cool

重定向会影响到这个:

example.com/path/&test=123&lol=cool

但想拥有这个:

example.com/path/

我怎么能这样做?

Kob*_*obi 632

你可以做一个相对重定向:

window.location.href = '../'; //one level up
Run Code Online (Sandbox Code Playgroud)

要么

window.location.href = '/path'; //relative to domain
Run Code Online (Sandbox Code Playgroud)

  • 当你想模拟一个链接时,你应该使用`window.location.href`.当您想要模拟http重定向(因此不生成历史项)时,您应该只使用`window.location.replace`. (48认同)
  • 看看你为什么要使用`window.location.replace` http://stackoverflow.com/questions/503093/how-can-i-make-a-redirect-page-in-jquery/506004#506004 (25认同)
  • 顺便说一句,`document.location`旨在作为只读属性.使用`window.location`更安全.请参阅[此问题](http://stackoverflow.com/questions/2430936/whats-the-difference-between-window-location-and-document-location-in-javascript). (23认同)
  • 我发现使用`window.location.href ='../'`重定向到站点的根目录而不是按预期"一级".当前页面是"www.example.com/customers/list"时,我需要使用`'./'`.我想这是因为"list"不被视为目录级别. (6认同)
  • @MarcusCunningham,在你的例子中,目录是/ customers/ - 所以"一级"是www.example.com/.现在,如果您的示例网址是www.example.com/customers/list/,则会将您重定向到www.example.com/customers/ (2认同)

Bob*_*Bob 12

如果您使用,location.hostname您将获得domain.com部分.然后location.pathname会给你/ path /文件夹.我会拆分location.pathname/并重新组合URL.但除非您需要查询字符串,否则您只需重定向..即可转到上面的目录.


Chr*_*nce 8

重定向到 ../


Kor*_*nel 6

<a href="..">no JS needed</a>

.. 表示父目录.

  • 这需要点击或其他一些用户启动的导航. (12认同)

Sha*_*tin 6

https://developer.mozilla.org/zh-CN/docs/Web/API/Location/assign

  • window.location.assign("../"); //上一层
  • window.location.assign("/path"); //相对于域