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

我正在基于php的网站上使用javascript / jquery,我必须在页面中的事件上重定向页面。

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

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

就像是:

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

谢谢。

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

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

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

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

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

要么

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

或者在jquery ……

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

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

看一下window.location上的MDN文档 :

如果我理解,如果你在http://example.com/path/to/page1.php上 ,并点击“page2.php”,你希望被重定向到http://example.com/path /to/page2.php ?

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

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

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