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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12508225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:34:31  来源:igfitidea点击:

How do we update URL or query strings using javascript/jQuery without reloading the page?

javascriptjquery

提问by developarvin

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

有没有办法在不重新加载页面的情况下以编程方式更新 URL?

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

编辑:我在帖子的标题中添加了一些内容。我只是想明确表示我不想重新加载页面

采纳答案by Matt Fellows

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

是的 - 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:

location 对象也有许多有用的属性:

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

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

编辑:设置 document.location 的哈希值不应重新加载页面,只需更改焦点在页面上的位置即可。所以更新到#myId将滚动到带有id="myId". 如果id不存在我相信什么都不会发生?(虽然需要在各种浏览器上确认)

EDIT2: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.

EDIT2:要说清楚,不仅仅是在评论中:您不能在不更改页面的情况下使用 javascript 更新整个 URL,这是一个安全限制。否则你可以点击一个链接到一个随机页面,看起来像 gmail,然后立即将 URL 更改为 www.gmail.com 并窃取人们的登录详细信息。
您可以在某些浏览器上更改域后的部分以处理 AJAX 样式的内容,但这已经被 Osiris 链接到了。更重要的是,您可能不应该这样做,即使可以。URL 告诉用户他/她在您网站上的位置。如果您在不更改页面内容的情况下更改它,则会变得有点混乱。

回答by Fabio Nolasco

Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.

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

However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:

然而,一些 HTML5 兼容的网络浏览器已经实现了一个 History API,可以用于类似于你想要的东西:

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

I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.

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

For more information:

想要查询更多的信息:

http://diveintohtml5.info/history.html

http://diveintohtml5.info/history.html

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

回答by Sud

You can use :

您可以使用 :

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

回答by Prasad De Silva

Use

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

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

To update Url without reloadingthe page

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

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

To remove Query string without reloadingthe page

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

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

回答by MasNotsram

Yes

是的

document.location is the normal way.

document.location 是正常方式。

However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.

然而,document.location 实际上与 window.location 相同,只是 window.location 在较旧的浏览器中受到更多支持,因此可能是最好的选择。

Check out this thread on SO for more info:

在 SO 上查看此线程以获取更多信息:

What's the difference between window.location and document.location in JavaScript?

JavaScript 中的 window.location 和 document.location 有什么区别?

回答by Ronnie Royston

Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.

定义一个新的 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);

回答by Timothy Gonzalez

Prefix URL changes with a hashtag to avoid a redirect.

使用主题标签更改前缀 URL 以避免重定向。

This redirects

这重定向

location.href += '&test='true';

This doesn't redirect

这不会重定向

location.href += '#&test='true';

回答by Osiris

You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.

你需要更具体。“更新网址”是什么意思?这可能意味着自动导航到不同的页面,这当然是可能的。

If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page

如果你只想更新地址栏的内容而不重新加载页面,请参阅修改URL而不重新加载页面

回答by Claus

Plain javascript: document.location = 'http://www.google.com';

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

This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.

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

回答by Roman

Yes - document.location.hashfor queries

是 -document.location.hash用于查询