如何在不重新加载页面的情况下使用javascript / jQuery更新URL或查询字符串?


76

有没有一种方法可以以编程方式更新URL而无需重新加载页面?

编辑:我在帖子的标题中添加了一些内容。我只想清楚一点,就是我不想重新加载页面


举例说明您要达到的目标。
康斯坦丁·迪涅夫

您是否要更改DOM中的可见URL(在地址栏中)或文档URL字符串?
莫里斯·

@Maurice我只是想改变显示的网址
developarvin

本例中使用window.history.replaceState()
Prasad De Silva,

Answers:


40

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

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

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

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

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不存在,我相信什么都不会发生?(不过需要在各种浏览器上进行确认)

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


1
我正在查看所有URL的更新,而不仅仅是散列数据的更新
developerarvin 2012年

4
您不能在不更改页面的情况下使用javascript更新整个URL,这是一项安全限制。否则,您可以单击指向随机页面的链接,然后立即将URL设为www.gmail.com并窃取用户的登录信息。
Matt Fellows 2012年

21
设置document.location重新加载页面。
2014年

谢谢@AlainTiemblo-如果您阅读了完整的答案,您将看到我已经承认的警告,并承认这一点。
Matt Fellows 2014年

很好的深入解释。
2016年

93

是的,没有。所有常见的Web浏览器都有防止这种情况的安全措施。目的是防止人们创建网站副本,更改URL使其看起来正确,然后能够欺骗人们并获取其信息。

但是,某些与HTML5兼容的Web浏览器已实现了History API,该API可用于类似于您想要的内容:

if (history.pushState) {
    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
    window.history.pushState({path:newurl},'',newurl);
}

我进行了测试,并且效果很好。它不会重新加载页面,但仅允许您更改URL查询。您将无法更改协议或主机值。

想要查询更多的信息:

http://diveintohtml5.info/history.html

https://developer.mozilla.org/zh-CN/docs/Web/Guide/API/DOM/Manipulating_the_browser_history


单击“返回”将删除更改,但我喜欢这个主意。
Alain Tiemblo 2014年

这种方法在某些浏览器中不起作用,因为它window.location.pathname包含一个斜杠/,并且结果值可以http://my.domain.com/?myNewUrlQuery=1代替http://my.domain.com?myNewUrlQuery=1
pto3

7

您可以使用 :

window.history.pushState('obj', 'newtitle', newUrlWithQueryString)

或window.history.replaceState('obj','newtitle',newUrlWithQueryString),如果您不想在历史记录中保存url更改。
TamusJRoyce '19

4

使用

window.history.replaceState({},document.title,UpdatedUri);

不重新加载页面的情况下更新网址

 var url = window.location.href;
 var urlParts = url.split('?');
 if (urlParts.length > 0) {
     var baseUrl = urlParts[0];
     var queryString = urlParts[1];

     //update queryString in here...I have added a new string at the end in this example
     var updatedQueryString = queryString + 'this_is_the_new_url' 

     var updatedUri = baseUrl + '?' + updatedQueryString;
     window.history.replaceState({}, document.title, updatedUri);
 }

不重新加载页面的情况下删除查询字符串

var url = window.location.href;
if (url.indexOf("?") > 0) {
     var updatedUri = url.substring(0, url.indexOf("?"));
     window.history.replaceState({}, document.title, updatedUri);
}

我只是在查看Mozilla的文档window.history.replaceState()因为我不确定这三个参数的作用,您能解释一下吗?第二点,document.title似乎没有任何作用。
tfantina

replaceState()操作完全相同,pushState()因此请检查pushState()方法参数描述。 title该参数目前已被忽略,但他们将来可能会使用它。
普拉萨德席尔瓦


2

定义一个新的URL对象,为其分配当前的url,将您的参数附加到该URL对象上,最后将其推入浏览器状态。

var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);


0

普通的javascript:document.location ='http://www.google.com';

但是,这将导致浏览器刷新-如果需要更新URL来实现某种浏览历史记录而不重新加载页面,请考虑使用哈希。如果是这种情况,您可能希望研究jQuery.hashchange。


1
是的,它会导致浏览器刷新。正在寻找无法重新加载的内容。
developarvin

据我所知,应该可以不刷新页面而进行操作,但是只有更新的浏览器才支持它。您应该改为更改哈希网址。
克劳斯


-3

是-document.location.hash查询


1
它将重新加载页面。我正在寻找不删除页面的解决方案。
developarvin

是的,原因是,它会重新加载页面。您需要将此与ajax结合使用以获得新页面并插入其内容。
罗马

提出问题的人不想重新加载页面。
Chewie The Chorkie
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.