Javascript 如何使用javascript进行相对路径重定向?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8028737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:26:53  来源:igfitidea点击:

how to do a relative path redirection using javascript?

javascriptjquery

提问by arun nair

I'm working on javascript/jquery in a php based site, and I have to redirect the page upon an event in the page.

我正在基于 php 的站点中处理 javascript/jquery,我必须根据页面中的事件重定向页面。

lets say, on clicking the button "click me" in "page1.php", the page should be redirected to "page2.php". This redirection has to be done using javascript/ jquery. Both pages are in the same folder, and the redirection code should use 'RELATIVE LINKS'.

可以说,在单击 中的“单击我”按钮时"page1.php",页面应重定向到“ page2.php”。此重定向必须使用 javascript/jquery 完成。两个页面都在同一个文件夹中,重定向代码应该使用'RELATIVE LINKS'

Now, I am able to redirect if I give the absolute link to page2.php, but could someone let me know how to do the same with a relative link?

现在,如果我将绝对链接提供给 ,我就可以重定向page2.php,但是有人可以让我知道如何使用相对链接来做同样的事情吗?

something like:

就像是:

window.location.href = 'page2.php';

thanks.

谢谢。

回答by arun nair

window.location.href = "page2.php";

this worked. Infact, relative and absolute works in the same way:

这有效。事实上,相对和绝对的工作方式相同:

window.location.href = "http://www.google.com";
// or
window.location.href = "page2.html";

回答by Enigma State

You can do a relative redirect:

你可以做一个相对重定向:

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

or

或者

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

or in jquery ...

或在 jquery ...

 var url = "http://stackoverflow.com";    
$(location).attr('href',url);

回答by James Hill

To set a relative path use window.location.pathname.

要设置相对路径,请使用window.location.pathname.

Take a look at the MDN docson window.location:

看看的MDN文档window.location

回答by fflorent

If I understand, if you are on http://example.com/path/to/page1.php, and you click on "page2.php", you would like to be redirected to http://example.com/path/to/page2.php?

如果我理解,如果您在http://example.com/path/to/page1.php 上,然后单击“page2.php”,您希望被重定向到http://example.com/path /to/page2.php

Perhaps there is a smarter solution, but does it solve your problem ?

也许有一个更聪明的解决方案,但它能解决您的问题吗?

function relativeRedir(redir){
  location.pathname = location.pathname.replace(/(.*)\/[^/]*/, "/"+redir);
}

Example of use : relativeRedir("page1.php");

使用示例:relativeRedir("page1.php");