【问题标题】:How to use the URL filepath as parameters in plain html/javascript?如何在纯 html/javascript 中使用 URL 文件路径作为参数?
【发布时间】:2020-06-28 01:10:13
【问题描述】:

我知道设置和获取 URL 参数,例如example.com/index.html?x=foo&y=bar&z=hello 将使您的 JavaScript 访问 URL 中指定的 xyz 变量。

我希望的是相同的行为,但使用 URL 的文件路径部分。例如。 example.com/index.html/foo/bar/hello.

我怎样才能做到这一点?特别是,

  1. 即使指定了文件路径index.html/foo/bar/hello,如何确保浏览器知道转到index.html
  2. 如何将 URL 更新为 example.com/index.html/foo/bar/world,这样如果我在浏览器上按“返回”,它将返回到 example.com/index.html/foo/bar/hello

此外,如果解决方案是纯 javascript/html,不依赖 jquery 或任何其他库,我会非常喜欢。

【问题讨论】:

  • 但是/foo/bar/hello.应该是一个可以访问它的文件。
  • 如果index.html 之后的路径是 url 哈希值 .... example.com/index.html#/foo/bar/hello 可能更有意义。服务器只会知道index.html,而您的前端可以解析哈希以执行location.hash 所需的任何操作
  • 另一种选择是当存在其他路径部分时,您需要服务器端来管理发送 index.html。不知道你在服务器上使用什么堆栈
  • 这是只能在服务器端完成的事情
  • 所以我发现History.pushstate 可以使用window.history.pushState({x: "foo", y: "bar", z: "hello"}, "", "/foo/bar/hello") 完成此任务,并且导航工作正常且一切正常。唯一的问题是直接输入 url example.com/index.html/foo/bar/hello 将无法正常工作。你是说 URL 可以正常工作的唯一方法是弄乱服务器端,那么?

标签: javascript html url web-applications get


【解决方案1】:

您应该处理两种情况。

  1. 如果用户在一个外部页面上并希望使用链接 example.com/index.html/foo/bar 访问您的页面怎么办?这应该在服务器而不是客户端处理。
  2. 如果用户已经在某个页面上,例如 example.com/index.html 并且想要转到 example.com/index.html/foo/bar,您可以使用 pushState 方法。您可以查看 https://developer.mozilla.org/en-US/docs/Web/API/History/pushState 来更改当前的 URL & 和这个 https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate 在用户按下后退按钮时执行某些操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-27
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    相关资源
    最近更新 更多