admin管理员组文章数量:1290949
I'm looking for the simplest way to add parameters to a URL and then reload the page via javascript/jquery. I'm trying to avoid any plugins. Essentially I want:
to bee:
or, if a parameter already exists, then add a second parameter:
;qa=newParam
I'm looking for the simplest way to add parameters to a URL and then reload the page via javascript/jquery. I'm trying to avoid any plugins. Essentially I want:
http://www.mysite./about
to bee:
http://www.mysite./about?qa=newParam
or, if a parameter already exists, then add a second parameter:
http://www.mysite./about?qa=oldParam&qa=newParam
Share
Improve this question
asked Mar 10, 2014 at 21:44
cc-testcc-test
431 gold badge3 silver badges11 bronze badges
3 Answers
Reset to default 3Here is a vanilla solution, it should work nicely for all cases (except wrong inputs of course).
function replace_search(name, value) {
var str = location.search;
if (new RegExp("[&?]"+name+"([=&].+)?$").test(str)) {
str = str.replace(new RegExp("(?:[&?])"+name+"[^&]*", "g"), "")
}
str += "&";
str += name + "=" + value;
str = "?" + str.slice(1);
// there is an official order for the query and the hash if you didn't know.
location.assign(location.origin + location.pathname + str + location.hash)
};
EDIT: if you want to add stuff and never remove anything the function is way smaller. I'm not very found of having multiple fields with different values but there is no specifications on that.
function replace_search(name, value) {
var str = "";
if (location.search.length == 0) {
str = "?"
} else {
str = "&"
}
str += name + "=" + value;
location.assign(location.origin + location.pathname + location.search + str + location.hash)
};
Have a look at Window.location (MDN) for information on window.location
.
A quick and dirty solution is:
location += (location.search ? "&" : "?") + "qa=newParam"
It should work for your example, but misses some edge cases.
location.href
will give you the current URL. You can then edit your query string and refresh the page by doing something like this:
if (location.href.indexOf("?") === -1) {
window.location = location.href += "?qa=newParam";
}
else {
window.location = location.href += "&qa=newParam";
}
本文标签: javascriptHow do you add a parameter to a URL and reload the pageStack Overflow
版权声明:本文标题:javascript - How do you add a parameter to a URL and reload the page - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741507496a2382407.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论