javascript 在 url 中附加参数而不重新加载页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10445229/
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
Append parameter in url without reloading page
提问by Manoj Patil
I am using following code to append param to url. This is working fine but when parameter is appended in url, page is getting reloaded. I want to use this functionality without reloading the page .
我正在使用以下代码将参数附加到 url。这工作正常,但是当参数附加到 url 时,页面正在重新加载。我想在不重新加载页面的情况下使用此功能。
function insertParam(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
alert('sdfadsf');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
//alert(document.location.href);
}
}
I want to add multiple params to url without reloading the page like:
我想在不重新加载页面的情况下向 url 添加多个参数,例如:
- txt1
- txt2
- txt3
- txt1
- txt2
- txt3
- link1
- link2
- link3
- 链接1
- 链接2
- 链接3
i want url : "..../search.php"
我想要网址:“..../search.php”
after click on txt2 i want url : "..../search.php#t_2"
单击 txt2 后,我想要 url:“..../search.php#t_2”
after click on link2 i want url : "..../search.php#t_1&l_2"
点击link2后我想要网址:“..../search.php#t_1&l_2”
回答by Alnitak
You can only do this using history.pushState(state, title, url)
which is an HTML5 feature.
您只能使用history.pushState(state, title, url)
HTML5 功能来执行此操作。
回答by Artem Kovalov
There is a new feature that aims to replace the use of location.hash
with a better solution: pushState
.
有一个新功能旨在location.hash
用更好的解决方案取代 的使用:pushState
.
window.history.pushState(data, "Title", "/new-url");
More information: http://badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate
更多信息:http: //badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate