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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5895151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:43:37  来源:igfitidea点击:

Can I change the URL string in the address bar using javascript

javascriptjquery

提问by ptamzz

I've a link on my webpage, say 'about'. Clicking on it loads a particular div without refreshing the whole page using jquery .load(). This does not change the URL string in the browser address bar.

我在我的网页上有一个链接,说“关于”。单击它会加载一个特定的 div,而无需使用 jquery 刷新整个页面.load()。这不会更改浏览器地址栏中的 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??

可以这样做吗??

采纳答案by Felix Kling

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).

  • In browsers which don't support this, you can only change the fragment identifier #without reloading the page (via the locationobject). That means you have to change the URL to e.g.

    www.mydomain.com/#!page=about
    

    #!is a convention from Google to make Ajax sites crawlable. 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.
    There are jQuery pluginsthat help you to handler this.

  • 在较新的浏览器中,您可以使用HTML5 历史 API,它可以更改 URL 的一部分,以及查询字符串(和路径 afaik)。

  • 在不支持此功能的浏览器中,您只能更改片段标识符#而无需重新加载页面(通过location对象)。这意味着您必须将 URL 更改为例如

    www.mydomain.com/#!page=about
    

    #!是 Google 的一项约定,目的是使 Ajax 站点可抓取。由于片段标识符没有发送到服务器,您必须使用 JavaScript 检测它并从服务器加载相应的数据。
    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 并回退到基于哈希的解决方案。



As written in my comment, you can also find more information here:

正如我的评论中所写,您还可以在此处找到更多信息:

回答by Atticus

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.

您可以更改位置的其他属性,不确定它的名称是什么“?”,可能是查询字符串、获取或类似的东西。