简体   繁体   English

如何使用 URL 文件路径作为纯 html/javascript 中的参数?

[英]How to use the URL filepath as parameters in plain html/javascript?

I know about setting and getting URL parameters, eg example.com/index.html?x=foo&y=bar&z=hello would give your javascript access to the x , y , and z variables specified in the URL. I know about setting and getting URL parameters, eg example.com/index.html?x=foo&y=bar&z=hello would give your javascript access to the x , y , and z variables specified in the URL.

What I wish for is the same behavior but utilizing the file path part of the URL.我希望的是相同的行为,但使用 URL 的文件路径部分。 Eg example.com/index.html/foo/bar/hello .例如example.com/index.html/foo/bar/hello

How can I accomplish this?我怎样才能做到这一点? In particular,尤其是,

  1. How can I make sure the browser knows to go to index.html even though the file path index.html/foo/bar/hello was specified?即使指定了文件路径index.html/foo/bar/hello ,如何确保浏览器知道 go 到index.html
  2. How can I update the URL to example.com/index.html/foo/bar/world , such that if I press "Back" on the browser, it will go back to example.com/index.html/foo/bar/hello .如何将 URL 更新为example.com/index.html/foo/bar/world ,这样如果我在浏览器上按“返回”,它将 go 返回example.com/index.html/foo/bar/hello

Furthermore, I'd heavily prefer if the solution was in pure javascript/html, without reliance on jquery or any other libraries.此外,如果解决方案是纯 javascript/html,而不依赖于 jquery 或任何其他库,我会非常喜欢。

There's 2 scenarios you should handle.您应该处理两种情况。

  1. What if the user is on a foreign page and wants to visit your page using the link example.com/index.html/foo/bar?如果用户在一个外部页面上并想使用链接 example.com/index.html/foo/bar 访问您的页面怎么办? This should be handled on the server not on the client side.这应该在服务器而不是客户端处理。
  2. If the user is already on some page, say example.com/index.html and wants to go to example.com/index.html/foo/bar, you may use the pushState method.如果用户已经在某个页面上,例如 example.com/index.html 并且想要 go 到 example.com/index.html/foo/bar,您可以使用 pushState 方法。 You may look at https://developer.mozilla.org/en-US/docs/Web/API/History/pushState to change the current URL & and this https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate to do something when the user presses the back button. You may look at https://developer.mozilla.org/en-US/docs/Web/API/History/pushState to change the current URL & and this https://developer.mozilla.org/en-US/docs /Web/API/WindowEventHandlers/onpopstate在用户按下后退按钮时执行某些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM