js代码实现
使用 window.location.href 实现页面跳转
通过修改 window.location.href 属性可以直接跳转到指定 URL。这种方式会记录到浏览器的历史记录中,用户可以通过后退按钮返回前一页。
window.location.href = "https://example.com";
使用 window.location.replace 实现无历史记录跳转
window.location.replace 方法会替换当前页面,不会在浏览器的历史记录中留下痕迹,用户无法通过后退按钮返回前一页。
window.location.replace("https://example.com");
使用 window.open 在新窗口或标签页打开链接
window.open 方法可以在新窗口或标签页中打开指定的 URL。可以通过参数控制窗口的行为,例如是否显示工具栏、是否可调整大小等。
window.open("https://example.com", "_blank");
使用 location.assign 方法跳转
location.assign 方法类似于 window.location.href,会加载新的页面并记录到浏览器的历史记录中。

location.assign("https://example.com");
使用 meta 标签自动跳转
在 HTML 中使用 <meta> 标签的 http-equiv="refresh" 属性可以实现自动跳转。这种方式适用于静态页面或服务器端渲染的场景。
<meta http-equiv="refresh" content="5; url=https://example.com">
使用 JavaScript 定时跳转
通过 setTimeout 结合 window.location 可以实现延迟跳转,适用于需要等待几秒后再跳转的场景。

setTimeout(function() {
window.location.href = "https://example.com";
}, 3000); // 3 秒后跳转
使用表单提交跳转
如果需要传递数据,可以通过动态创建表单并提交的方式实现跳转。
const form = document.createElement("form");
form.method = "POST";
form.action = "https://example.com";
document.body.appendChild(form);
form.submit();
使用 history.pushState 无刷新修改 URL
如果仅需修改 URL 而不刷新页面,可以使用 history.pushState 方法。适用于单页应用(SPA)的场景。
history.pushState({}, "", "https://example.com/new-path");
使用 fetch 和 window.location 结合
在发送异步请求后,根据返回结果决定是否跳转页面。
fetch("/api/check-auth")
.then(response => response.json())
.then(data => {
if (data.authenticated) {
window.location.href = "/dashboard";
}
});






