如何在URL中添加参数? [英] How to add a parameter to the URL?

查看:241
本文介绍了如何在URL中添加参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的网址是: http://something.com/mobiles.php?brand=samsung

现在,当用户点击最低价格过滤器(比如300)时,我希望我的网址变为

Now when a user clicks on a minimum price filter (say 300), I want my URL to become

http://something.com /mobiles.php?brand=samsung&priceMin=300

换句话说,我正在寻找一个将添加指定的javascript函数当前URL中的参数,然后将网页重定向到新URL。

In other words, I am looking for a javascript function which will add a specified parameter in the current URL and then re-direct the webpage to the new URL.

注意:如果没有设置参数,那么该函数应该添加而不是& ;

Note: If no parameters are set then the function should add ? instead of &

ie如果当前网址为 http://something.com/mobiles.php ,则应将网页重定向到 http://something.com /mobiles.php?priceMin=300
而不是 http://something.com/mobiles.php&priceMin=300

i.e. if the current URL is http://something.com/mobiles.php then page should be re-directed to http://something.com/mobiles.php?priceMin=300 instead of http://something.com/mobiles.php&priceMin=300

推荐答案

尝试类似这样的事情,它也应该考虑你已经在url中有这个参数的情况:

try something like this, it should consider also cases when you already have that param in url:

function addOrUpdateUrlParam(name, value)
{
  var href = window.location.href;
  var regex = new RegExp("[&\\?]" + name + "=");
  if(regex.test(href))
  {
    regex = new RegExp("([&\\?])" + name + "=\\d+");
    window.location.href = href.replace(regex, "$1" + name + "=" + value);
  }
  else
  {
    if(href.indexOf("?") > -1)
      window.location.href = href + "&" + name + "=" + value;
    else
      window.location.href = href + "?" + name + "=" + value;
  }
}

然后你就像你的情况一样调用它:

then you invoke it like in your case:

addOrUpdateUrlParam('priceMin', 300);

这篇关于如何在URL中添加参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆