简体   繁体   English

我可以使用 javascript 更改地址栏中的 URL 字符串吗

[英]Can I change the URL string in the address bar using javascript

I've a link on my webpage, say 'about'.我的网页上有一个链接,说“关于”。 Clicking on it loads a particular div without refreshing the whole page using jquery .load() .单击它会加载特定的 div 而不会使用 jquery .load .load()刷新整个页面。 This does not change the URL string in the browser address bar.这不会更改浏览器地址栏中的 URL 字符串。

The same page can be accessed by going to www.mydomain.com/?page=about .可以通过访问www.mydomain.com/?page=about访问同一页面。

So what I want to do is, when the user clicks on the 'about' link, the pages will be loaded as it is (using jquery), but I want to change the URL string in the browser address bar also so that someone can actually copy or bookmark the exact page.所以我想要做的是,当用户点击“关于”链接时,页面将按原样加载(使用 jquery),但我想更改浏览器地址栏中的 URL 字符串,以便有人可以实际复制或添加书签的确切页面。

Is it possible to do so??有可能这样做吗?

You have two possibilites to tackle this problem:你有两种可能来解决这个问题:

  • In newer browsers you can make use of the HTML5 history API , which lets change part of the URL, also the query string (and path afaik).在较新的浏览器中,您可以使用HTML5 历史 API ,它可以更改 URL 的一部分,以及查询字符串(和路径 afaik)。

  • In browsers which don't support this, you can only change the fragment identifier # without reloading the page (via the location object).在不支持此功能的浏览器中,您只能更改片段标识符#而无需重新加载页面(通过location对象)。 That means you have to change the URL to eg这意味着您必须将 URL 更改为例如

    www.mydomain.com/#!page=about

    #! is a convention from Google to make Ajax sites crawlable .是 Google 的约定,旨在使 Ajax 网站可抓取 As the fragment identifier is not sent to the server, you have to detect it with JavaScript and load the corresponding data from the server.由于片段标识符没有发送到服务器,因此您必须使用 JavaScript 检测它并从服务器加载相应的数据。
    There are jQuery plugins that help you to handler this.jQuery 插件可以帮助您处理这个问题。

I would look for a good plugin makes use of the history API if available and falls back to the hash based solution.我会寻找一个好的插件,利用历史 API(如果可用)并回退到基于 hash 的解决方案。


As written in my comment, you can also find more information here:正如我在评论中所写,您还可以在此处找到更多信息:

Yes, I've done it by doing是的,我已经做到了

location.hash = 'foo';

There's other attributes of location you can change, not sure what it's called for '?', probably query-string, get, or soemthing like that.您可以更改位置的其他属性,不确定“?”的名称,可能是查询字符串、get 或类似的东西。

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

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