如何使用window.location.replace JavaScript? [英] How to use window.location.replace javascript?

查看:81
本文介绍了如何使用window.location.replace JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网址

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

重定向页面

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

我想从page1.aspx重定向到page2.aspx

如何在page1.aspx中编写JavaScript?

How to write a javascript in page1.aspx?

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

前2个给了我这个.

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

最后1个给了我

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

正确的使用方式是什么?

What is the correct way to use?

推荐答案

完全不包含路径信息,就像在链接中一样:

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

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

这是一个实时示例该示例在

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

...和

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

...因此2页面使用

window.location.replace("3");

...并且3页面使用

window.location.replace("2");

有关URL(尤其是相对URL)如何工作的更多信息,请参见 RFC3986 .但基本上:

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

  • 如果相对URL 不是./开头,它将替换最后一个段.所以:

  • 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

  • 如果相对URL以../开头,它将替换最后一个段:

  • 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
    

    请注意,two子文件夹已被替换.多个../可用于上移多个级别:

    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
    

  • 如果相对URL以单个/开头,它将替换主机名(和端口(如果有))之后的所有内容.所以:

  • 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
    

  • 如果相对URL以//开头,它将替换协议中的所有内容,因此:

  • If a relative URL starts with //, it replaces everything following the protocol, so:

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

    (这在加载资源时很方便,并且您要避免担心httphttps和混合内容警告.)

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

    这篇关于如何使用window.location.replace JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆