简体   繁体   中英

Redirecting to a relative URL in JavaScript

My problem is that I want to redirect via JavaScript to a directory above.

My code:

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

The URL looks like this:

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

The redirect affect just this:

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

But want to have this:

example.com/path/

How can I do it?

You can do a relative redirect:

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

or

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

If you use location.hostname you will get your domain.com part. Then location.pathname will give you /path/folder. I would split location.pathname by / and reassemble the URL. But unless you need the querystring, you can just redirect to .. to go a directory above.

重定向到../

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

..表示父目录。

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

  • window.location.assign("../"); // one level up
  • window.location.assign("/path"); // relative to domain

I'm trying to redirect my current web site to other section on the same page, using JavaScript. This follow code work for me:

location.href='/otherSection'

尝试遵循js代码

 location = '..' 

This is an old question but just to provide more information, this is how urls work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM