Possible Duplicate:
Modify Address Bar URL in AJAX App to Match Current State

How can I change the URL address without redirecting the page?

For instance, when I click on this link below:

<a href="http://mysite.com/projects/article-1" class="get-article">link</a>

I will grab the URL from the link:

var path = object.attr('href');

如果我在下面这样做,页面将被重定向:

window.location = path;

I want to do something like this site, when you click on the image, the ajax call will fetch the requested page and the URL address on the window will be changed too, so that it has a path for what you click.

推荐答案

注意:现在支持history.pushState()-请参阅其他答案.

You cannot change the whole url without redirecting, what you can do instead is change the hash.

The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable.


If applied well, this technique is useful in two ways:

  1. 浏览器历史记录将记住您采取的每一个不同步骤(因为url+哈希已更改)
  2. you can have an address which links not only to a particular html document, but also gives your javascript a clue about what to do. That means you end up pointing to a state inside your web app.

To change the hash you can do:

document.location.hash = "show_picture";

To watch for hash changes you have to do something like:

window.onhashchange = function(){
    var what_to_do = document.location.hash;    
    if (what_to_do=="#show_picture")
        show_picture();
}

当然,散列只是一个字符串,所以你可以用它做你喜欢的事情.例如,如果使用JSON将整个对象放入其中,则可以将其放入其中.

有非常好的JQuery库可以用来做高级的事情.

Jquery相关问答推荐

从克隆的输入中读取数据属性,返回初始输入的值

使用 shell 脚本判断 json 数组响应是否具有特定用户名和状态的 jq 命令

哪个 JQuery Select 器会排除与给定 Select 器匹配的父项的项目?

如何在jQuery中移动表格行?

jquery克隆div并将其附加在特定div之后

表单提交之前的jQuery函数

JSLint 错误:将调用移动到包含函数的括号中

javascript:无效(0); vs 返回 false vs preventDefault()

jQuery 滚动到 Div

jQuery 与 ExtJS

我如何从 ACE 编辑器中获得价值?

非 AJAX jQuery POST 请求

在完成前一个请求之前中止新的 AJAX 请求

如果不是 jQuery,Javascript 中的美元符号是什么

使用 JavaScript 获取用户代理

jQuery: Select 所有具有自定义属性的元素

5秒后jQuery自动隐藏元素

jQuery - 从元素内部 Select 元素

在 jquery 中使用 AJAX Post 从强类型 MVC3 视图传递模型的正确方法

detach()、hide() 和 remove() 之间的区别 - jQuery