【问题标题】:How do you add a parameter to a URL and reload the page如何将参数添加到 URL 并重新加载页面
【发布时间】:2014-04-14 06:05:21
【问题描述】:

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

http://www.mysite.com/about

变成:

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

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

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

【问题讨论】:

    标签: javascript jquery url parameters


    【解决方案1】:

    这是一个普通的解决方案,它应该适用于所有情况(当然输入错误除外)。

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

    【讨论】:

    • 这很好用。我添加了一个 if/else 语句来检测参数是否已经存在。非常感谢。
    【解决方案2】:

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

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

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

    它应该适用于您的示例,但会遗漏一些边缘情况。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 我尝试使用它,但由于某种原因,它会创建一个无限循环,不断添加参数。不知道为什么,因为我认为条件会处理这个问题。
      • @cc-test 是不是你只是在<script> 标签中裸露了这些行?在这种情况下,它们将在页面加载时执行,从而导致重定向。是这样,然后尝试将它放在像@username的解决方案这样的函数中,并在您想要重新加载页面时调用它。
      猜你喜欢
      • 2019-03-08
      • 1970-01-01
      • 2020-08-23
      • 2020-03-19
      • 1970-01-01
      • 2022-09-27
      • 2017-01-24
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多