且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 AJAX 调用上更新 URL?

更新时间:2022-06-27 07:06:34

不,这是不可能的.更新:现在可以通过 HTML5 History API 实现 - 参见 razbakov 的回答.

Nope, this is not possible. Update: It is now possible via the HTML5 History API - see razbakov's answer.

我希望您意识到您正在努力解决一个极其困难的问题.

I hope you realize that you are trying to address an extremely difficult problem.

假设您的网址看起来像

http://example.com/mypage/

如果您以编程方式将窗口位置更改为

If you change the window location programmatically to

http://example/mypage/1/

浏览器将接管并尝试导航到该页面,您喜欢的 ajax 代码就在这里!

Browser will take over and try to navigate to that page, there goes your fancy ajax code!

那么有什么办法呢?您使用 URL 片段.

So what's the alternative? You use URL fragment.

假设您有一个这样的网址,

Let's say you have a URL like this,

http://example.com/anotherpage/#section

浏览器将首先加载 http://example.com/anotherpage/ 并尝试找到一个锚点命名为部分"并滚动到该位置.地址"插件利用了这种行为.这类似于那些滚动到顶部"链接的工作方式.

Browser will first load http://example.com/anotherpage/ and try to find an anchor named 'section' and scroll to that location. This behavior is exploited by the 'Addresses' plugin. This is similar to how those 'Scroll To Top' links work.

所以如果你在页面上

http://example.com/mypage/

并将 URL 更改为

http://example.com/mypage/#1

浏览器不会加载新页面,而是尝试查找名为1"的锚点并滚动到该锚点.

Browser will not load new page but rather try to find anchor named '1' and scroll to that anchor.

即使您已设法向 URL 添加片段,也不意味着工作已完成.如果用户按下后退按钮,DOM 将被重置,您将不得不解析这些片段并重新创建 DOM.这绝对是不平凡的.

Even if you have managed to add fragments to the URL, it doesn't mean the work is done. If the user presses the back button, DOM will be reset and you will have to parse those fragments and recreate the DOM. It's definitely non-trivial.