修改 AJAX 应用程序中的地址栏 URL 以匹配当前状态 [英] Modify Address Bar URL in AJAX App to Match Current State

查看:20
本文介绍了修改 AJAX 应用程序中的地址栏 URL 以匹配当前状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 AJAX 应用程序,但是当用户在应用程序中移动时,尽管没有页面重新加载,我还是希望地址栏中的 URL 更新.基本上,我希望他们能够在任何时候添加书签,从而返回到当前状态.

I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state.

人们如何在 AJAX 应用程序中维护 REST 性?

How are people handling maintaining RESTfulness in AJAX apps?

推荐答案

这样做的方法是在 AJAX 更新导致您想要的状态更改时操作 location.hash一个离散的 URL.例如,如果您的网页网址是:

The way to do this is to manipulate location.hash when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is:

http://example.com/

如果客户端函数执行了此代码:

If a client side function executed this code:

// AJAX code to display the "foo" state goes here.

location.hash = 'foo';

然后,浏览器中显示的 URL 将更新为:

Then, the URL displayed in the browser would be updated to:

http://example.com/#foo

这允许用户为页面的foo"状态添加书签,并使用浏览器历史记录在状态之间导航.

This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states.

有了这个机制,你就需要在客户端使用 JavaScript 解析出 URL 的哈希部分来创建和显示适当的初始状态,因为片段标识符(# 之后的部分)不是发送到服务器.

With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server.

Ben Alman 的 hashchange 插件 如果您正在使用,则后者轻而易举jQuery.

Ben Alman's hashchange plugin makes the latter a breeze if you're using jQuery.

这篇关于修改 AJAX 应用程序中的地址栏 URL 以匹配当前状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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