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相关问答推荐

无法在被动事件侦听器中阻止默认值

JQuery:如果 div 可见

从客户端的对象数组中获取最新日期的优雅方法是什么?

在页面加载之间保持变量

catch forEach 最后一次迭代

如何滚动到AngularJS中的页面顶部?

用布尔值隐藏/显示元素

如何在 bootstrap 模式关闭并重新打开时重置 bootstrap 模式?

删除索引后的所有项目

将返回的 JSON 对象属性转换为(较低的第一个)camelCase

你能在不影响历史的情况下使用哈希导航吗?

将图像 url 转换为 Base64

如何使 Bootstrap 轮播滑块使用移动左/右滑动

jquery - 单击事件不适用于动态创建的按钮

在jQuery中获取所有选定复选框值的最佳方法

将打开/关闭图标添加到 Twitter Bootstrap 可折叠项(手风琴)

jQuery - 使用发布数据重定向

等效于 C# LINQ Select 的 Javascript

选择select2后触发动作

Jquery:如何在按下回车键时触发点击事件