迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中重定向到相对的 URL

作者:迹忆客 最近更新:2023/03/10 浏览次数:

在你的网站上,你可能需要经常重定向页面。虽然建议从服务器端转网页和 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 重定向相对 URL

当你单击重定向页面按钮时,页面链接将被重定向,如下所示:

JavaScript 重定向页面

请注意以下事项:

  • 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 提交表单,然后根据按钮的回答进行重定向。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便