jquery:更改 URL 地址而不重定向? [英] jquery: change the URL address without redirecting?

查看:67
本文介绍了jquery:更改 URL 地址而不重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
修改 AJAX 应用中的地址栏 URL 以匹配当前状态

如何在不重定向页面的情况下更改 URL 地址?

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>

我将从链接中获取 URL:

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;

我想做这样的事情网站,当你单击图像,ajax 调用将获取请求的页面,窗口上的 URL 地址也将更改,以便它具有您单击的路径.

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() - 查看其他答案.

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.

hash 是网址中# 符号之后的部分.这最初是为了将您(本地)定向到 HTML 文档的各个部分,但您可以通过 javascript 读取和修改它以使用它有点像全局变量.

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+hash 改变了)
  2. 您可以拥有一个地址,该地址不仅可以链接到特定的 html 文档,还可以为您的 javascript 提供有关该做什么的线索.这意味着您最终会指向网络应用内的一个状态.

<小时>

要更改哈希,您可以执行以下操作:

document.location.hash = "show_picture";

<小时>

要观察哈希更改,您必须执行以下操作:

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

<小时>

当然散列只是一个字符串,所以你可以用它做任何你喜欢的事情.例如,如果您使用 JSON 来字符串化,您可以将整个对象放在那里.


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.

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

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

这篇关于jquery:更改 URL 地址而不重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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