如何使用 Javascript 设置查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5546207/
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
How to set querystring with Javascript
提问by rsturim
Is there a way to set the values of a querystring using javascript?
有没有办法使用javascript设置查询字符串的值?
My page has a filter list that when clicked, it will alter the in-page results pane on the right hand side.
我的页面有一个过滤器列表,单击该列表后,它会更改右侧的页内结果窗格。
I'm trying to update to the querystring values of the url, so if the user leaves the page, then clicks the "back" buttons they'll be return to the last filter selection set.
我正在尝试更新 url 的查询字符串值,因此如果用户离开页面,然后单击“返回”按钮,他们将返回到最后一个过滤器选择集。
For example:
Landing: foo.html
Click 1: foo.html?facets=bar
Click 2: foo.html?facets=bar|baz
Click 3: foo.html?facets=bar|baz|zap
例如:
登陆:foo.html
点击 1:foo.html?facets=bar
点击 2:foo.html?facets=bar|baz
点击 3:foo.html?facets=bar|baz|zap
Is this possible?
这可能吗?
采纳答案by Kelly
You can use Javascript to change the hash (the #hash-part of the URL), but changing the query string means you have to reload the page. So, no, what you want to do is not possible in that way.
您可以使用 Javascript 来更改哈希值(URL 的 #hash 部分),但更改查询字符串意味着您必须重新加载页面。所以,不,你想做的事情是不可能的。
An alternative is to use Javascript to change the hash, then check the hash on page load to change your results dynamically. You're looking for something like jQuery Address.
另一种方法是使用 Javascript 更改哈希,然后在页面加载时检查哈希以动态更改结果。您正在寻找类似jQuery Address 的东西。
回答by Dryden Williams
const params = new URLSearchParams(location.search);
params.set('test', 123);
params.set('cheese', 'yummy');
params.toString(); // => test=123&cheese=yummy
window.history.replaceState({}, '', `${location.pathname}?${params.toString()}`);
回答by Peter Olson
It is possible, but it will refresh the page.
这是可能的,但它会刷新页面。
document.location = "?facets=bar";
If you don't care about browser support, you can use the HTML5 history.pushState.
如果你不关心浏览器支持,你可以使用 HTML5 history.pushState。