繁体   English   中英

如何将参数添加到URL并重新加载页面

[英]How do you add a parameter to a URL and reload the page

我正在寻找向URL添加参数,然后通过javascript / jquery重新加载页面的最简单方法。 我正在尝试避免使用任何插件。 本质上我想要:

http://www.mysite.com/about

成为:

http://www.mysite.com/about?qa=newParam

或者,如果参数已经存在,则添加第二个参数:

http://www.mysite.com/about?qa=oldParam&qa=newParam

location.href将为您提供当前URL。 然后,您可以编辑查询字符串并通过执行以下操作刷新页面:

if (location.href.indexOf("?") === -1) {
    window.location = location.href += "?qa=newParam";
}
else {
    window.location = location.href += "&qa=newParam";
}

查看window.location(MDN),以获取有关window.location信息。

一个快速而肮脏的解决方案是:

location += (location.search ? "&" : "?") + "qa=newParam"

它适用于您的示例,但是遗漏了一些极端情况。

这是一个很好的解决方案,它在所有情况下都可以很好地工作(当然,错误的输入除外)。

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

编辑:如果您想添加东西而从不删除任何内容,则该函数要小得多。 我不是很想知道具有多个具有不同值的字段,但是对此没有任何说明。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM