在JavaScript中重定向到相对URL

494

我的问题是,我想通过JavaScript将重定向到上一级目录。

我的代码:

location.href = (location.href).substr(0, (location.href).lastIndexOf('folder'))

这个URL看起来像这样:

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

重定向只影响这个部分:

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

但是想要的是这个:

example.com/path/

我该怎么做?

8个回答

913

你可以进行相对路径重定向:

window.location.href = '../'; //one level up
或者
window.location.href = '/path'; //relative to domain

44
了解为什么应该使用window.location.replace请参考:https://dev59.com/_3RB5IYBdhLWcg3wz6Wd#506004 - gideon
76
当您想模拟一个链接时,应该使用 window.location.href。只有当您想模拟一个 HTTP 重定向(因此不会生成历史记录项)时,才应该使用 window.location.replace - Benji XVI
29
顺便说一下,“document.location”被设计为只读属性。更安全的做法是使用“window.location”。请参见此问题 - Benji XVI
9
我发现使用 window.location.href = '../' 会将页面重定向到站点根目录,而不是像预期的那样“上一级”目录。 当前页面为“www.example.com/customers/list”时,我需要使用 './'。 我猜这是因为“list”不被视为一个目录级别。 - Marcus Cunningham
8
在你的例子中,目录是 /customers/ - 所以 "上一级" 是 www.example.com/。现在如果你的示例 URL 是 www.example.com/customers/list/,它会重定向到 www.example.com/customers/。 - Ubeogesh

18

如果您使用location.hostname,您将获得您的域名.com部分。然后location.pathname将给您/path/folder。我会通过/拆分location.pathname并重新组装URL。但是,除非您需要查询字符串,否则可以只重定向到..以进入上一级目录。


当我使用 location.path 时,我的浏览器会出现错误提示,似乎只能识别 location.pathname。有什么建议吗? - Konrad Viltersten
location.path不正确,应该是location.hostname。我已经在帖子中添加了编辑来修复这个问题。 - ygrichman

16

1
"/path"不能被分配使用。它不包括域名,只是尝试打开“/path”。 - Pumuckelo

12

重定向到../


1
如果您的应用程序托管在子 URI 中,并且应用程序不知道子 URI 路径。 如果您在应用程序根目录处执行 ../,则应用程序将不知道如何返回到其根目录。 例如,相同的应用程序托管在 http://example.com/myapp/ 和 http://other.example.com/app2/ 上。 - ReggieB

6

16
需要点击或其他用户主动导航才能实现。 - recursive

4

我想使用JavaScript将当前网站重定向到同一页面上的其他部分。以下代码对我有效:

location.href='/otherSection'

3

这是一个老问题,但为了提供更多信息,以下是url的工作原理:

window.location.href = 'https://domain/path';   // absolute
window.location.href = '//domain/path';         // relative to current schema
window.location.href = 'path';                  // relative to current path
window.location.href = '/path';                 // relative to domain
window.location.href = '../';                   // one level up

2
最初的回答:

尝试以下JavaScript代码

location = '..'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接