如何使用 jQuery 或 JavaScript 将用户从一个页面重定向到另一个页面?
window.location.href("http://www.baidu.com");这是直接跳转
这个问题呀,那方法可多了:
// 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 buenoself.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')
提示! 如果非要用jQuery,那么我的回答解决不了这个问题,用jQuery还是不行啊。 相反,还是用 JavaScript 吧。
$(location).attr('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 粘贴、会话等)进行测试,可以判断请求是否合法。 (注意: 还有一些方法可以绕过这些引用)
还有简单的方法,跨浏览器测试解决问题(回到 window.location.href,用于 Internet Explorer 9 以及所有其他浏览器)
酱紫用: 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;
}}
一般不用 jquery 重定向
jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
别用jQuery ,用window.location.replace(...)更容易模拟 HTTP 重定向。
用window.location.replace(...) 比 window.location.href 要好,因为 replace()不会在会话历史记录中保留原始页面,这意味着用户不会陷入无休止的后退失败。
如果您想模拟某人单击某个链接,请使用 location.href
如果您想模拟 HTTP 重定向,可以使用 ocation.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";