在 AJAX 调用上更新 URL? [英] Update URL on AJAX call?

查看:27
本文介绍了在 AJAX 调用上更新 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我在使用 AJAX 时遇到的最大问题是,如果我在一个页面上使用 AJAX,转到另一个页面,然后使用浏览器的后退按钮返回使用 AJAX 更改的任何内容都消失了.

Right now the biggest issue I'm having with using AJAX is the fact that if I use AJAX on a page, go to another page, then use the browser's back button to go back anything that was changed with AJAX is gone.

我想过使用 jQuery Addresss 插件来解决这个问题,但我没有不喜欢它只用#whatever.html"修改 URL 而不是完全改变它.

I've thought about using the jQuery Addresss plugin to solve that problem but I don't like how it only amends the URL with "#whatever.html" instead of changing it completely.

理想情况下,当我进行相关的 AJAX 调用时,我希望 URL 从www.example.com/p:2/"变为www.example.com/p:3/".

Ideally, what I would like is to have the URL go from: "www.example.com/p:2/" to "www.example.com/p:3/" when I make the relevant AJAX call.

这可能吗?

推荐答案

不,这是不可能的.更新:现在可以通过 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.

这篇关于在 AJAX 调用上更新 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆