Reputation: 3683
I'm working on javascript/jquery in a php based site, and I have to redirect the page upon an event in the page.
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'.
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?
something like:
window.location.href = 'page2.php';
thanks.
Upvotes: 25
Views: 102744
Reputation: 1646
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 ?
Perhaps there is a smarter solution, but does it solve your problem ?
function relativeRedir(redir){
location.pathname = location.pathname.replace(/(.*)\/[^/]*/, "$1/"+redir);
}
Example of use : relativeRedir("page1.php");
Upvotes: 3
Reputation: 3683
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";
Upvotes: 33
Reputation: 61812
To set a relative path use window.location.pathname
.
Take a look at the MDN docs on window.location
:
Upvotes: 6
Reputation: 17701
You can do a relative redirect:
document.location.href = '../'; //one level up
or
document.location.href = '/path'; //relative to domain
or in jquery ...
var url = "http://stackoverflow.com";
$(location).attr('href',url);
Upvotes: 14