如何在不重新加载页面的情况下使用javascript/jQuery更新URL或查询字符串? [英] How do we update URL or query strings using javascript/jQuery without reloading the page?

查看:105
本文介绍了如何在不重新加载页面的情况下使用javascript/jQuery更新URL或查询字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过编程方式更新URL而不重新加载页面?

Is there a way to update the URL programatically without reloading the page?

我在帖子的标题中添加了一些内容.我只是想表明我不想重新加载页面

I added something in the title in post .I just want to make it clear that I don't want to reload the page

推荐答案

是-document.location = "http://my.new.url.com"

您也可以用相同的方式检索它,例如.

You can also retrieve it the same way eg.

var myURL = document.location;
document.location = myURL + "?a=parameter";

位置对象也具有许多有用的属性:

The location object has a number of useful properties too:

hash            Returns the anchor portion of a URL
host            Returns the hostname and port of a URL
hostname        Returns the hostname of a URL
href            Returns the entire URL
pathname        Returns the path name of a URL
port            Returns the port number the server uses for a URL
protocol        Returns the protocol of a URL
search          Returns the query portion of a URL

设置document.location的哈希值不应重新加载页面,而只需更改焦点在页面上的位置即可.因此,更新到#myId将滚动到带有id="myId"的元素.如果id不存在,我相信什么都不会发生? (不过需要在各种浏览器上进行确认)

Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)

EDIT2 :为了清楚起见,不仅仅是在注释中: 您不能在不更改页面的情况下使用javascript更新整个URL,这是一项安全限制.否则,您可以单击指向随机页面的链接,该页面的外观设计类似于gmail,然后立即将URL更改为www.gmail.com并窃取用户的登录详细信息.
您可以在某些浏览器上更改域后的部分,以应对AJAX样式的问题,但这已由Osiris链接到该部分.而且,即使可以,您也可能不应该这样做.该URL告诉用户他/她在您网站上的位置.如果您在不更改页面内容的情况下对其进行了更改,则会变得有些混乱.

To make it clear, not just in a comment: You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.

这篇关于如何在不重新加载页面的情况下使用javascript/jQuery更新URL或查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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