ChatGPT解决这个技术问题 Extra ChatGPT

重定向到 JavaScript 中的相对 URL

我的问题是我想通过 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/

我该怎么做?


K
Kobi

您可以进行相对重定向:

window.location.href = '../'; //one level up

或者

window.location.href = '/path'; //relative to domain

看看为什么你应该使用 window.location.replace stackoverflow.com/questions/503093/…
当您要模拟链接时,您应该使用 window.location.href。当您想模拟 http 重定向(因此不生成历史项目)时,您应该只使用 window.location.replace
顺便说一句,document.location 旨在作为只读属性。使用 window.location 更安全。请参阅this question
我发现使用 window.location.href = '../' 重定向到站点的根目录,而不是像预期的那样“向上一级”。当当前页面是“www.example.com/customers/list”时,我需要使用 './'。我猜这是因为“列表”不被视为目录级别。
@MarcusCunningham,在您的示例中,目录是 /customers/ - 所以“上一级”是 www.example.com/。现在,如果您的示例 URL 是 www.example.com/customers/list/ - 它会将您重定向到 www.example.com/customers/
y
ygrichman

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


当我转到 location.path 时,我的浏览器会吠叫,它似乎只能识别 location.pathname。提示?
location.path 不正确,应该是 location.hostname。我已经在帖子中添加了一个编辑来解决这个问题。
S
Shaun Luttin

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

window.location.assign("../"); // 上一级

window.location.assign("/path"); // 相对于域


C
Chris Ballance

重定向到 ../


如果您的应用程序托管在子 uri 中并且应用程序不知道子 uri 路径。如果你在你的应用程序根目录并且你做了 ../ 应用程序将不知道如何回到它的根目录。例如,同一应用程序托管在 example.com/myappother.example.com/app2
K
Kornel

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

.. 表示父目录。


这需要单击或其他一些用户启动的导航。
T
Timo Tijhof

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

location.href='/otherSection'

K
Kamil Kiełczewski

试试下面的js代码

位置 = '..'