Javascript 如何将网页从一个域重定向到另一个域?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3450351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect webpage from one domain to another?
提问by user415997
How to redirect domain to another domain, when the first domain (webpage) load?
当第一个域(网页)加载时,如何将域重定向到另一个域?
回答by BalusC
A pure HTML alternative is the following <meta>tag in your HTML <head>:
纯 HTML 替代方案是 HTML 中的以下<meta>标记<head>:
<meta http-equiv="refresh" content="0;http://anotherdomain.com">
The 0is here the amount of seconds the page has to stay open before redirecting. In this case, it'll happen immediately as soon as you loads the page. In contrary to the proposed JS solution, this will work fine as well in browsers with JS disabled.
这0是页面在重定向之前必须保持打开的秒数。在这种情况下,它会在您加载页面后立即发生。与建议的 JS 解决方案相反,这在禁用 JS 的浏览器中也能正常工作。
However, if you've the ability to hook on server side code without trouble (i.e. response is not committed yet and so on), then I'd prefer that above the HTML/JS solution anyway.
但是,如果您能够毫无问题地挂钩服务器端代码(即尚未提交响应等),那么无论如何我都希望将其置于 HTML/JS 解决方案之上。
回答by Barlow Tucker
There are a couple of ways to do this. One is to add the an onload event to the body tag what sets window.location to the new domain.
有几种方法可以做到这一点。一种是将 onload 事件添加到将 window.location 设置为新域的 body 标记。
<script language=javascript>
function redirect(){
window.location = "http://example.com";
}
</script>
<body onload="redirect()">
</body>

