本文翻译自:Redirecting to a relative URL in JavaScript
I have a problem: I want to redirect via JavaScript to a directory above. 我有一个问题:我想通过JavaScript重定向到上面的目录。 My code: 我的代码:
location.href = (location.href).substr(0, (location.href).lastIndexOf('folder'));
The URL looks like this: URL如下所示:
example.com/path/folder/index.php?file=abc&test=123&lol=cool example.com/path/folder/index.php?file=abc&test=123&lol=cool
The redirect affect just this: 重定向会影响到这个:
example.com/path/&test=123&lol=cool example.com/path/&test=123&lol=cool
But want to have this: 但想拥有这个:
example.com/path/ example.com/path/
How could I do that? 我怎么能这样做?
#1楼
参考:https://stackoom.com/question/6wYb/重定向到JavaScript中的相对URL
#2楼
重定向到../
#3楼
If you use location.hostname
you will get your domain.com part. 如果您使用location.hostname
您将获得domain.com部分。 Then location.pathname
will give you /path/folder. 然后location.pathname
将为您提供/ path /文件夹。 I would split location.pathname
by / and reassemble the URL. 我会将location.pathname
拆分为/并重新组合URL。 But unless you need the querystring, you can just redirect to ..
to go a directory above. 但除非您需要查询字符串,否则您只需重定向到..
即可转到上面的目录。
#4楼
<a href="..">no JS needed</a>
..
表示父目录。
#5楼
You can do a relative redirect: 你可以做一个相对重定向:
window.location.href = '../'; //one level up
or 要么
window.location.href = '/path'; //relative to domain
#6楼
I'm trying to redirect my current web site to other section on the same page, using JavaScript. 我正在尝试使用JavaScript将我当前的网站重定向到同一页面上的其他部分。 This follow code work for me: 以下代码适用于我:
location.href='/otherSection'