JavaScript 中重定向到相对的 URL
在你的网站上,你可能需要经常重定向页面。虽然建议从服务器端转网页和 URL,但在某些情况下,你可能需要使用 JavaScript 从客户端重定向页面。
我们将在本教程中了解如何使用 JavaScript 进行转换。
尽管大多数 JavaScript 库(例如 jQuery)都具有重定向网页的预制函数,但使用纯 JavaScript 总是更直接。有两种 JavaScript 重定向方法。
考虑你希望重新路由到 www.newwebsite.com/new-location
的场景。在这种情况下,你可以在网页的 JS 代码中包含以下命令之一。
语法:
window.location.replace("/url or path"); //or
window.location.href = "/url or path";
重定向首先不会将记录添加到浏览器的历史记录中。但是,类似于从你的网站单击另一个 URL,将在第二个实例中添加描述。
例子:
<!DOCTYPE html>
<html>
<head>
<script>
function nUrl() {
window.location.href = "b.html";
}
</script>
</head>
<body>
<input type="button" value="Redirect page" onclick="nUrl()" />
</body>
</html>
输出:
当你单击重定向页面
按钮时,页面链接将被重定向,如下所示:
请注意以下事项:
- JavaScript 不能用于从 HTTPS 网页重定向到 HTTP 网站。大多数浏览器不会让你这样做。
- 你可以使用 JavaScript 从 HTTP 重定向到 HTTP、HTTP 到 HTTPS 和 HTTPS 仅重定向到 HTTPS 页面。你必须使用从 HTTPS 到 HTTP 网站的服务器端重定向。
- 你可以使用绝对路径(如 /new-location)或完整的 URL(如 http://www.newwebsite.com/new-location)。如果你指定重定向的相对路径,浏览器将使用相同的 HTTP/HTTPS 协议重新路由到网站,而无需修改它。
- 最好提供整个 URL 以从 HTTP 重定向到 HTTPS 页面。
- 如果你将重定向放在 Submit 按钮的函数处理程序中,它可能不起作用,因为浏览器将提交表单而不是重新路由页面。在这些情况下,你可以使用 AJAX 提交表单,然后根据按钮的回答进行重定向。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。