重定向到JavaScript中的相对URL

本文探讨如何使用JavaScript进行相对URL重定向,尤其是如何从当前URL重定向到其上一级目录。讨论中提到,可以使用window.location.pathname获取路径名,结合需求进行URL重组或直接使用相对路径'..'来实现上一级目录的跳转。
摘要由CSDN通过智能技术生成

本文翻译自: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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值