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');

If I do this below, the page will be redirected:

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.

推荐答案

NOTE: history.pushState() is now supported - see other answers.

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. the browser history will remember each different step you took (since the url+hash changed)
  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();
}

Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.

There are very good JQuery libraries to do advanced things with that.

Jquery相关问答推荐

在添加_renderMenu方法时,是什么原因导致jQuery UI AutoComplete抛出TypeError?

在 Mastodon 中将 jQuery 添加到 Rails 6

JQuery AJAX 成功事件未触发

在不同的行插入不同的值

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

jQuery .first() 方法返回第一个元素的集合

如何使用 JQuery Select 没有特定子元素的元素

如何在 jQuery 中 Select 特定的表单元素?

jquery清除输入默认值

使用 jQuery Validate 确认密码

jQuery Select 一个具有某个类的div,它没有另一个类

jQuery scrollTop 在 Chrome 中不工作但在 Firefox 中工作

如何使用 jQuery Select 的插件重置表单?

使用 jquery/ajax 刷新/重新加载 Div 中的内容

如何通过 DOM 容器访问 Highcharts 图表?

在不丢失光标位置的情况下更新输入值

使用 Jquery 查找父 div 的 id

如何将键和值都推送到 Jquery 中的数组中

.animate() 的回调被调用两次 jquery

jQuery 使用 AND 和 OR 运算符按属性 Select