如何使用JavaScript重定向?

Ms_*_*y13 933 javascript redirect

如何使用JavaScript从另一个页面重定向到页面?

see*_*edg 1471

要重定向到另一个页面,您可以使用:

window.location = "http://www.yoururl.com";
Run Code Online (Sandbox Code Playgroud)

  • @JFA你可以在一个超时函数中嵌入window.location,如下所示:`t1 = window.setTimeout(function(){window.location ="http://www.yoururl.com";},3000);`其中3000是3秒. (47认同)
  • window.location.href ="example"; 可能是更好的做法,因为浏览器策略可能限制其使用并阻止它,因为.location和.location.href不完全相同.但是在某些情况下,使用.location是理想的,特别是如果您使用相同的原始策略(如iframe). (14认同)
  • 如何在延迟几秒后实现这一目标? (5认同)
  • window.location.href = "http://www.yoururl.com"; (2认同)

sid*_*mor 246

window.location.replace('http://sidanmor.com');
Run Code Online (Sandbox Code Playgroud)

它比使用更好window.location.href = 'http://sidanmor.com';

使用replace()更好是因为它不会将原始页面保留在会话历史记录中,这意味着用户不会陷入永无止境的后退按钮惨败.

如果您想模拟某人点击链接,请使用 window.location.href

如果要模拟HTTP重定向,请使用 window.location.replace

例如:

// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");

// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";
Run Code Online (Sandbox Code Playgroud)

从这里开始: 如何在jQuery中重定向到另一个页面?

  • 这绝对是正确的答案,但是应该注意,“ replace()”可能并不总是最佳选择。如果在完成AJAX调用或其他操作后正在重定向,则可能希望将原始页面保留在历史记录中。这真的取决于情况! (3认同)
  • **这个答案完全是误导!**没有“更好”,特别是没有粗体写的“更好”。使用`replace`或`href`取决于用例。我个人主要使用“ href”,因为大多数时候我需要让用户返回。 (2认同)

Sha*_*ard 55

您无法重定向到某个功能.您可以做的是在重定向时在URL上传递一些标志,然后在服务器端代码中检查该标志,如果引发该标志,则执行该功能.

例如:

document.location = "MyPage.php?action=DoThis";
Run Code Online (Sandbox Code Playgroud)

然后在您的PHP代码中检查查询字符串中的"action",如果等于"DoThis",则执行您需要的任何函数.


Kip*_*Kip 35

  • 如果您想模拟某人点击链接,请使用location.href.
  • 如果要模拟HTTP重定向,请使用location.replace.

例如:

// Similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// Similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
Run Code Online (Sandbox Code Playgroud)

从此答案复制到重复问题的信息


Fen*_*ton 32

您可能需要再解释一下您的问题.

当您说"重定向"时,对于建议更改HTML页面位置的大多数人:

window.location = url;
Run Code Online (Sandbox Code Playgroud)

当你说"重定向到功能"时 - 它真的没有意义.您可以调用函数,也可以重定向到其他页面.您甚至可以重定向并在加载新页面时调用一个函数.