如何重定向到另一个网页?

7702

如何使用jQuery或纯JavaScript将用户从一个页面重定向到另一个页面?

58个回答

16250

使用jQuery并不简单地进行重定向

jQuery并不是必需的,而window.location.replace(...)将最好地模拟HTTP重定向。

window.location.replace(...)比使用window.location.href更好,因为replace()不会在会话历史中保留原始页面,这意味着用户不会陷入无休止的后退按钮困境。

如果你想模拟某人点击链接,使用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";

45
注意:replace() 方法与 HTTP 重定向类似,它不会在浏览器历史记录中创建条目。 - png
7
如果你只是想展示一个重定向页面,用location.replace()可能更合适(这样可以将带有重定向的页面从浏览历史记录中排除)。但是为什么不一开始就在服务器端进行重定向呢? - x-yuri
3
如果有人仍然遇到了问题,即使应用了所有优秀的答案,页面重定向仍然无法正常工作,请访问以下链接:https://dev59.com/YGUo5IYBdhLWcg3wzCBr这对我的情况起作用。 - Md. Jamal Uddin
@bart 有一种框架,其中哈希紧随域名后面(https://example.com/#some/path)?此外,打开另一页和重定向之间有什么区别?在我看来,重定向意味着想要显示页面B而不是页面A。如果该内容不在服务器上,那么为什么不立即显示页面B,而要进行重定向呢? - x-yuri
2
在我的情况下,我移动了服务来提供带有URI片段的URL,并希望人们可能已经收藏的旧超链接通过重定向到新站点并保留片段继续工作。你说得对,这个框架之所以使用片段而不是查询参数,原因不明。 - bart
显示剩余2条评论

1831

警告:本答案仅作为可能的解决方案提供,显然不是最佳解决方案,因为它需要使用jQuery。相反,请优先选择纯JavaScript解决方案。

$(location).prop('href', 'http://stackoverflow.com')

828

将页面重定向的标准“纯”JavaScript方法

window.location.href = 'newPage.html';

更简单地说:(因为window是全局的)
location.href = 'newPage.html';

如果您在重定向时丢失HTTP_REFERER,请继续阅读:
(否则请忽略此部分)
以下内容适用于那些将HTTP_REFERER作为多种安全措施之一的人(尽管它不是一个很好的保护措施)。如果您使用Internet Explorer 8或更低版本,则在使用任何形式的JavaScript页面重定向(location.href等)时,这些变量会丢失。
下面我们将实现一个替代方案,以便在IE8及更低版本中不丢失HTTP_REFERER。否则,您几乎总是可以简单地使用window.location.href
针对HTTP_REFERER(URL粘贴,会话等)的测试可以帮助确定请求是否合法。 注意:还有一些方法可以绕过/欺骗这些引荐者,如droop评论中的链接所述)
简单的跨浏览器测试解决方案(Internet Explorer 9+和其他所有浏览器回退到window.location.href)。
用法:redirect('anotherpage.aspx');
function redirect (url) {
    var ua        = navigator.userAgent.toLowerCase(),
        isIE      = ua.indexOf('msie') !== -1,
        version   = parseInt(ua.substr(4, 2), 10);

    // Internet Explorer 8 and lower
    if (isIE && version < 9) {
        var link = document.createElement('a');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }

    // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
    else { 
        window.location.href = url; 
    }
}

504

有很多方法可以做到这一点。

// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'

// window.history
window.history.back()
window.history.go(-1)

// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')


// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';

// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')


368

这适用于所有浏览器:

window.location.href = 'your_url';

321

如果你能在描述你所尝试做的事情方面更加详细一些,那将有所帮助。如果你正在尝试生成分页数据,那么有几种不同的方式可以实现。你可以为每个要直接访问的页面生成单独的链接。

<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...

请注意,在示例中,当前页面在代码和CSS中处理方式不同。

如果您想通过AJAX更改分页数据,则需要使用jQuery。您需要为每个对应不同页面的锚点标签添加一个点击处理程序。此点击处理程序将调用一些jQuery代码,通过AJAX获取下一页并更新表格中的新数据。以下示例假设您有一个返回新页面数据的Web服务。

$(document).ready( function() {
    $('a.pager-link').click( function() {
        var page = $(this).attr('href').split(/\?/)[1];
        $.ajax({
            type: 'POST',
            url: '/path-to-service',
            data: page,
            success: function(content) {
               $('#myTable').html(content);  // replace
            }
        });
        return false; // to stop link
    });
});

275
我认为location.replace(URL)是最好的方法,但如果您想通知搜索引擎有关重定向的信息(它们不分析JavaScript代码以查看重定向),则应将rel="canonical"元标记添加到您的网站中。
在其中添加一个具有HTML刷新元标记的noscript部分也是一个不错的解决方案。建议您使用这个JavaScript重定向工具来创建重定向。它还支持Internet Explorer以传递HTTP referrer。
没有延迟的示例代码如下:
<!-- Place this snippet right after opening the head tag to make it work properly -->

<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->

<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.example/"/>
<noscript>
    <meta http-equiv="refresh" content="0;URL=https://yourdomain.example/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
    var url = "https://yourdomain.example/";
    if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
    {
        document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
        var referLink = document.createElement("a");
        referLink.href = url;
        document.body.appendChild(referLink);
        referLink.click();
    }
    else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->

2
这个说法已经不再正确,搜索引擎现在可以分析Javascript。 - Jay
网站 insider.zone 似乎已经停止运营了(https://downforeveryoneorjustme.com/insider.zone)。 - JeFawk

240

但如果有人想要重定向回主页,那么可以使用以下代码片段。

window.location = window.location.host

如果你拥有开发、暂存和生产三种不同的环境,那将会非常有帮助。

你可以在Chrome控制台或Firebug控制台中输入这些关键词来探索窗口或窗口位置对象。


226

JavaScript提供了许多方法来检索和更改浏览器地址栏中显示的当前URL。所有这些方法都使用Location对象,该对象是Window对象的一个属性。您可以创建一个新的Location对象,其当前URL如下所示..

var currentLocation = window.location;

URL的基本结构

<protocol>//<hostname>:<port>/<pathname><search><hash>

enter image description here

  1. 协议(protocol) -- 指定访问互联网上资源所使用的协议名称。 (HTTP(未加密)或HTTPS(加密))

  2. 主机名(hostname) -- 主机名指定拥有资源的主机。例如,www.stackoverflow.com。服务器使用主机名提供服务。

  3. 端口(port) -- 端口号用于识别网络消息到达服务器时要转发到哪个特定进程。

  4. 路径(pathname) -- 路径包含关于Web客户端想要访问的主机内特定资源的信息。例如,stackoverflow.com/index.html。

  5. 查询(query) -- 查询字符串紧随路径组件之后,并提供一串信息,该资源可以利用这些信息进行某些目的(例如,作为搜索参数或要处理的数据)。

  6. 哈希(hash) -- URL的锚部分,包括哈希符号(#)。

通过这些Location对象属性,您可以访问所有这些URL组件。

  1. hash -设置或返回URL的锚部分。
  2. host -设置或返回URL的主机名和端口。
  3. hostname -设置或返回URL的主机名。
  4. href -设置或返回整个URL。
  5. pathname -设置或返回URL的路径名。
  6. port -设置或返回服务器用于URL的端口号。
  7. protocol -设置或返回URL的协议。
  8. search -设置或返回URL的查询部分。

现在,如果您要更改页面或将用户重定向到其他页面,则可以使用Location对象的href属性,如下所示:

您可以使用Location对象的href属性。

window.location.href = "http://www.stackoverflow.com";

位置对象还具有以下三种方法:

  1. assign() -- 加载新文档。
  2. reload() -- 重新加载当前文档。
  3. replace() -- 用新文档替换当前文档。

您也可以使用assign()和replace方法将页面重定向到其他页面,如下所示:

location.assign("http://www.stackoverflow.com");

location.replace("http://www.stackoverflow.com");

assign() 和 replace() 的区别 -- replace() 方法和 assign() 方法的区别在于,replace() 方法会从文档历史记录中删除当前文档的 URL,这意味着无法使用“后退”按钮导航回原始文档。因此,如果您想加载一个新文档,并希望提供导航回原始文档的选项,请使用 assign() 方法。

您也可以像这样使用 jQuery 更改 location 对象的 href 属性。

$(location).attr('href',url);

因此,您可以将用户重定向到其他网址。


216

基本上,jQuery只是一个JavaScript框架,在某些情况下(如重定向),您可以只使用纯JavaScript来完成一些操作。在这种情况下,您有三个选项可以使用纯JavaScript:

1)使用位置replace,这将替换页面的当前历史记录,这意味着无法使用返回按钮返回到原始页面。

window.location.replace("http://stackoverflow.com");

2) 使用 assign 位置,这将为您保留历史记录,并使用后退按钮,您可以返回到原始页面:

window.location.assign("http://stackoverflow.com");

3)我建议使用之前提到的其中一种方式,但这也可以是第三个选项,使用纯JavaScript:

window.location.href="http://stackoverflow.com";

你也可以使用jQuery编写处理它的函数,但不建议这样做,因为它只是一个行纯JavaScript函数。如果你已经处于窗口作用域中,你也可以在不使用window的情况下使用上述所有函数,例如:window.location.replace("http://stackoverflow.com"); 可以简化为 location.replace("http://stackoverflow.com");

下面的图片展示了它们的所有内容:

location.replace location.assign


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接