在JavaScript中重定向到相对URL
我有一个问题: 我想通过JavaScript重定向到上面的目录。 我的代码: URL如下所示: example.com/path/folder/index.php?file=abc&test=123&lol=cool 重定向仅影响以下内容: example.com/path/&test=123&lol=cool 但是我想要这个: example.com/path/在JavaScript中重定向到相对URL,javascript,url,redirect,Javascript,Url,Redirect,我有一个问题: 我想通过JavaScript重定向到上面的目录。 我的代码: URL如下所示: example.com/path/folder/index.php?file=abc&test=123&lol=cool 重定向仅影响以下内容: example.com/path/&test=123&lol=cool 但是我想要这个: example.com/path/ 我该怎么做呢?重定向到。/如果您使用location.hostname,您将获得您的domain.com部分。然后location.
我该怎么做呢?重定向到
。/
如果您使用location.hostname
,您将获得您的domain.com部分。然后location.pathname
将为您提供/path/folder。我将通过/拆分location.pathname
,然后重新组装URL。但是,除非您需要查询字符串,否则您只需重定向到。
即可转到上面的目录。
。
表示父目录。您可以执行相对重定向:
window.location.href = '../'; //one level up
或
我正在尝试使用JavaScript将当前网站重定向到同一页面上的其他部分。以下代码适用于我:
location.href='/otherSection'
window.location.assign(“../”)代码>//向上一级
window.location.assign(“/path”)代码>//相对于域
location='..'
查看为什么应该使用window.location.replace
当您想要模拟链接时,应该使用window.location.href
。当您想要模拟http重定向(因此不生成历史记录项)时,您应该只使用window.location.replace
。顺便说一下,document.location
是一个只读属性。使用窗口位置更安全。请参阅。我发现使用window.location.href='../'
重定向到站点的根目录,而不是预期的“一级升级”。当当前页面为“www.example.com/customers/list”时,我需要使用。/”
。我想这是因为“列表”不被视为目录级别。@MarcusCunningham,在您的示例中,目录是/customers/,所以“一级升级”是www.example.com/。现在,如果您的示例URL是www.example.com/customers/list/,它会将您重定向到www.example.com/customers/,这需要单击或其他用户启动的导航。如果您的应用托管在子uri中,而该应用不知道子uri路径。如果你在应用程序根目录下,并且你在应用程序根目录下,应用程序将不知道如何返回其根目录。例如,同一个应用程序位于,当我转到location.path时,我的浏览器会发出吠声,它似乎只识别location.pathname。提示?location.path不正确,应该是location.hostname。我在帖子中添加了一个编辑来解决这个问题。
window.location.href = '/path'; //relative to domain
location.href='/otherSection'