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

IT技术 javascript jquery redirect
2020-12-09 22:20:01

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

6个回答

一个不是简单地使用 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";
@x-yuri 我的用例是 URI 片段(在 # 符号之后)不会通过服务器端重定向保留,因为它们没有发送到服务器。
2021-02-06 22:20:01
如果您显示一个页面只是为了进行重定向,location.replace()可能更合适(从历史记录中排除带有重定向的页面)。但是为什么不首先在服务器端进行重定向呢?
2021-02-15 22:20:01
在看到你的回答imgflip.com/i/11ua9c后,我在 5 年前创建了这个
2021-02-17 22:20:01
如果有人仍然遇到您应用的所有出色答案但页面重定向不起作用的问题,请访问:stackoverflow.com/questions/15759020/... 它适用于我的情况。
2021-02-21 22:20:01
注意:与 HTTP 重定向类似的行为replace()意味着它不会在浏览器的历史记录中创建条目。
2021-02-26 22:20:01

警告:此答案仅作为可能的解决方案提供;这显然不是最好的解决方案,因为它需要 jQuery。相反,更喜欢纯 JavaScript 解决方案。

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

重定向页面的标准“香草”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 粘贴、会话等)可以帮助判断请求是否合法。 注意:还有一些方法可以解决/欺骗这些推荐人,如评论中的下垂链接所指出的那样)


简单的跨浏览器测试解决方案(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; 
    }
}

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

// 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')

这适用于每个浏览器:

window.location.href = 'your_url';