Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use window.location.replace javascript?

Tags:

My URLs

http://www.mysite.com/folder1/page1.aspx http://www.mysite.com/folder1/page1.aspx?id=1 http://www.mysite.com/folder1/page1.aspx?id=1&dt=20111128 

Redirecting Page

http://www.mysite.com/folder1/page2.aspx 

I want to redirect from page1.aspx to page2.aspx

How to write a javascript in page1.aspx?

window.location.replace("/page2.aspx"); window.location.replace("../page2.aspx"); window.location.replace("~/page2.aspx"); 

First 2 gave me this.

http://www.mysite.com/page2.aspx 

Last 1 gave me this.

http://www.mysite.com/folder1/~/page2.aspx 

What is the correct way to use?

like image 490
william Avatar asked Nov 28 '11 09:11

william


1 Answers

Include no path information at all, just like in a link:

window.location.replace("page2.aspx"); 

Here's a live example The example switches between

http://jsbin.com/asupup/2   -- The "2" corresponds to your "page1.aspx"

...and

http://jsbin.com/asupup/3   -- The "3" corresponds to your "page2.aspx"

...and so the 2 page uses

window.location.replace("3"); 

...and the 3 page uses

window.location.replace("2"); 

For more about how URLs (and in particular relative URLs) work, see RFC3986. But basically:

  • If a relative URL doesn't start with . or /, it replaces the last segment. So:

        http://foo.com/one/two/page.html   + bar.html   = http://foo.com/one/two/bar.html 
  • If a relative URL starts with ../, it replaces the last segment and the one above it:

        http://foo.com/one/two/page.html   + ../bar.html   = http://foo.com/one/bar.html 

    Note that the two subfolder has been replaced. Multiple ../s can be used to move up multiple levels:

        http://foo.com/one/two/three/four/page.html   + ../../bar.html   = http://foo.com/one/two/bar.html 
  • If a relative URL starts with a single /, it replaces everything after the hostname (and port, if any). So:

        http://foo.com/one/two/page.html   + /bar.html   = http://foo.com/bar.html      http://foo.com:8080/one/two/page.html   + /bar.html   = http://foo.com:8080/bar.html 
  • If a relative URL starts with //, it replaces everything following the protocol, so:

        http://ex.com/folder/page.html   + //foo.com   = http://foo.com 

    (This is handy when loading resources and you want to avoid worrying about http vs. https and mixed-content warnings.)

like image 152
T.J. Crowder Avatar answered Sep 18 '22 12:09

T.J. Crowder