如何在URL中添加参数?

时间:2020-12-24 10:29:10

My current URL is: http://something.com/mobiles.php?brand=samsung

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

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

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

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

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.

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

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

注意:如果没有设置参数,那么该函数应该添加?代替 &

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是http://something.com/mobiles.php,则应将页面重定向到http://something.com/mobiles.php?priceMin=300而不是http://something.com/ mobiles.php&priceMin = 300

9 个解决方案

#1


16  

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

尝试这样的事情,它也应该考虑你已经在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);

#2


13  

Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:

实际上这完全是微不足道的,因为javascript位置对象已经处理了这个问题。只需将这个单行封装到一个函数中,即可通过链接等重复使用它:

<script>
    function addParam(v) {
        window.location.search += '&' + v;
    }
</script>

<a href="javascript:addParam('priceMin=300');">add priceMin=300</a>

There is no need to check for ? as this is already the search part and you only need to add the param.

没有必要检查?因为这已经是搜索部分,你只需要添加参数。

If you don't want to even make use of a function you can write as so:

如果您不想使用函数,可以这样写:

<a href="javascript:location.search+='&priceMin=300';">add priceMin=300</a>

Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.

请记住,这完全符合您的要求:添加该特定参数。它已经可以成为搜索部分的一部分,因为您可以在URI中多次使用相同的参数。您可能希望在应用程序中对其进行规范化,但这是另一个字段。我会将URL规范化集​​中到它自己的函数中。

Edit:

In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:

在讨论上面接受的答案时,很明显,应该满足以下条件才能获得有效的功能:

  • if the parameter already exists, it should be changed.
  • 如果参数已存在,则应更改。

  • if the parameter already exists multiple times, only the changed copy should survive.
  • 如果参数已多次存在,则只有更改的副本才能存在。

  • if the parameter already exists, but have no value, the value should be set.
  • 如果参数已存在但没有值,则应设置该值。

As search already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search:

由于搜索已经提供了搜索字符串,因此唯一要做的就是将查询信息部分解析为名称和值对,更改或添加缺少的名称和值,然后将其添加回搜索:

<script>
    function setParam(name, value) {
        var l = window.location;

        /* build params */
        var params = {};        
        var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;        
        var s = l.search;
        for(var r = x.exec(s); r; r = x.exec(s))
        {
            r[1] = decodeURIComponent(r[1]);
            if (!r[2]) r[2] = '%%';
            params[r[1]] = r[2];
        }

        /* set param */
        params[name] = encodeURIComponent(value);

        /* build search */
        var search = [];
        for(var i in params)
        {
            var p = encodeURIComponent(i);
            var v = params[i];
            if (v != '%%') p += '=' + v;
            search.push(p);
        }
        search = search.join('&');

        /* execute search */
        l.search = search;
    }
</script>

<a href="javascript:setParam('priceMin', 300);">add priceMin=300</a>

This at least is a bit more robust as it can deal with URLs like these:

这至少有点健壮,因为它可以处理这样的URL:

test.html?a?b&c&test=foo&priceMin=300

Or even:

test.html?a?b&c&test=foo&pri%63eMin=300

Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.

此外,添加的名称和值始终正确编码。如果参数名称导致非法属性js标签,则可能失败的地方。

#3


4  

if(location.search === "") {
    location.href = location.href + "?priceMin=300";
} else {
    location.href = location.href + "&priceMin=300";
}

In case location.search === "", then there is no ? part.

如果location.search ===“”,那么没有?部分。

So add ?newpart so that it becomes .php?newpart.

所以添加?newpart使它成为.php?newpart。

Otherwise there is a ? part already.

否则有一个?部分已经。

So add &newpart so that it becomes .php?existingpart&newpart.

所以添加&newpart使它成为.php?existingpart&newpart。


Thanks to hakre, you can also simply set it like:

感谢hakre,你也可以简单地设置它:

location.search += "&newpart";

It will automatically add ? if necessary (if not apparent, it will make it ?&newpart this way, but that should not matter).

它会自动添加?如果有必要(如果不明显,它会成功吗?&newpart这样,但这应该没关系)。

#4


2  

I rewrite the correct answer in PHP:

我用PHP重写了正确的答案:

function addOrUpdateUrlParam($name, $value){
$href = $_SERVER['REQUEST_URI'];
$regex = '/[&\\?]' . $name . "=/";
if(preg_match($regex, $href)){
    $regex = '([&\\?])'.$name.'=\\d+';
    $link = preg_replace($regex, "$1" . $name . "=" . $value, $href);
}else{
    if(strpos($href, '?')!=false){
        $link = $href . "&" . $name . "=" . $value;
    }else{
        $link = $href . "?" . $name . "=" . $value;
    }
}
return $link;
}

I hope that help's someone...

我希望帮助的人......

#5


1  

var applyMinPrice = function(minPrice) {
    var existingParams = (location.href.indexOf('?') !== -1),
        separator = existingParams ? '&' : '?',
        newParams = separator + 'priceMin=' + minPrice;

    location.href += newParams;
}

#6


0  

If you're having the user fill out a textfield with a minimum price, why not let the form submit as a GET-request with a blank action? IIRC, that should do just what you want, without any javascript.

如果您让用户以最低价格填写文本字段,为什么不让表单作为GET请求提交,并且空白操作? IIRC,这应该做你想要的,没有任何JavaScript。

#7


0  

<FORM action="" method="get">
<P>
<LABEL for="brand">Brand: </LABEL>
          <INPUT type="text" id="brand"><BR>
<LABEL for="priceMin">Minimum Price: </LABEL>
          <INPUT type="text" id="priceMin"><BR>
</P>

#8


0  

use var urlString = window.location to get the url

使用var urlString = window.location来获取url

check if the url already contains a '?' with urlString.indexOf('?'), -1 means it doesnt exist.

检查网址是否已包含“?”使用urlString.indexOf('?'),-1表示它不存在。

set window.location to redirect

将window.location设置为重定向

this is like 101 of javascript. try some search engines!

这就像是javascript的101。尝试一些搜索引擎!

#9


0  

<html>
<body>
..
..
..

<?php
$priceMinValue= addslashes ( $_GET['priceMin']);
if (!empty($priceMin)) {
        $link = "currentpage.php?priceMin=". $priceMinValue;
        die("<script>location.href = '".$link. "'</script>");    
}
?>
</body>
</html>

#1


16  

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

尝试这样的事情,它也应该考虑你已经在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);

#2


13  

Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:

实际上这完全是微不足道的,因为javascript位置对象已经处理了这个问题。只需将这个单行封装到一个函数中,即可通过链接等重复使用它:

<script>
    function addParam(v) {
        window.location.search += '&' + v;
    }
</script>

<a href="javascript:addParam('priceMin=300');">add priceMin=300</a>

There is no need to check for ? as this is already the search part and you only need to add the param.

没有必要检查?因为这已经是搜索部分,你只需要添加参数。

If you don't want to even make use of a function you can write as so:

如果您不想使用函数,可以这样写:

<a href="javascript:location.search+='&priceMin=300';">add priceMin=300</a>

Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.

请记住,这完全符合您的要求:添加该特定参数。它已经可以成为搜索部分的一部分,因为您可以在URI中多次使用相同的参数。您可能希望在应用程序中对其进行规范化,但这是另一个字段。我会将URL规范化集​​中到它自己的函数中。

Edit:

In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:

在讨论上面接受的答案时,很明显,应该满足以下条件才能获得有效的功能:

  • if the parameter already exists, it should be changed.
  • 如果参数已存在,则应更改。

  • if the parameter already exists multiple times, only the changed copy should survive.
  • 如果参数已多次存在,则只有更改的副本才能存在。

  • if the parameter already exists, but have no value, the value should be set.
  • 如果参数已存在但没有值,则应设置该值。

As search already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search:

由于搜索已经提供了搜索字符串,因此唯一要做的就是将查询信息部分解析为名称和值对,更改或添加缺少的名称和值,然后将其添加回搜索:

<script>
    function setParam(name, value) {
        var l = window.location;

        /* build params */
        var params = {};        
        var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;        
        var s = l.search;
        for(var r = x.exec(s); r; r = x.exec(s))
        {
            r[1] = decodeURIComponent(r[1]);
            if (!r[2]) r[2] = '%%';
            params[r[1]] = r[2];
        }

        /* set param */
        params[name] = encodeURIComponent(value);

        /* build search */
        var search = [];
        for(var i in params)
        {
            var p = encodeURIComponent(i);
            var v = params[i];
            if (v != '%%') p += '=' + v;
            search.push(p);
        }
        search = search.join('&');

        /* execute search */
        l.search = search;
    }
</script>

<a href="javascript:setParam('priceMin', 300);">add priceMin=300</a>

This at least is a bit more robust as it can deal with URLs like these:

这至少有点健壮,因为它可以处理这样的URL:

test.html?a?b&c&test=foo&priceMin=300

Or even:

test.html?a?b&c&test=foo&pri%63eMin=300

Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.

此外,添加的名称和值始终正确编码。如果参数名称导致非法属性js标签,则可能失败的地方。

#3


4  

if(location.search === "") {
    location.href = location.href + "?priceMin=300";
} else {
    location.href = location.href + "&priceMin=300";
}

In case location.search === "", then there is no ? part.

如果location.search ===“”,那么没有?部分。

So add ?newpart so that it becomes .php?newpart.

所以添加?newpart使它成为.php?newpart。

Otherwise there is a ? part already.

否则有一个?部分已经。

So add &newpart so that it becomes .php?existingpart&newpart.

所以添加&newpart使它成为.php?existingpart&newpart。


Thanks to hakre, you can also simply set it like:

感谢hakre,你也可以简单地设置它:

location.search += "&newpart";

It will automatically add ? if necessary (if not apparent, it will make it ?&newpart this way, but that should not matter).

它会自动添加?如果有必要(如果不明显,它会成功吗?&newpart这样,但这应该没关系)。

#4


2  

I rewrite the correct answer in PHP:

我用PHP重写了正确的答案:

function addOrUpdateUrlParam($name, $value){
$href = $_SERVER['REQUEST_URI'];
$regex = '/[&\\?]' . $name . "=/";
if(preg_match($regex, $href)){
    $regex = '([&\\?])'.$name.'=\\d+';
    $link = preg_replace($regex, "$1" . $name . "=" . $value, $href);
}else{
    if(strpos($href, '?')!=false){
        $link = $href . "&" . $name . "=" . $value;
    }else{
        $link = $href . "?" . $name . "=" . $value;
    }
}
return $link;
}

I hope that help's someone...

我希望帮助的人......

#5


1  

var applyMinPrice = function(minPrice) {
    var existingParams = (location.href.indexOf('?') !== -1),
        separator = existingParams ? '&' : '?',
        newParams = separator + 'priceMin=' + minPrice;

    location.href += newParams;
}

#6


0  

If you're having the user fill out a textfield with a minimum price, why not let the form submit as a GET-request with a blank action? IIRC, that should do just what you want, without any javascript.

如果您让用户以最低价格填写文本字段,为什么不让表单作为GET请求提交,并且空白操作? IIRC,这应该做你想要的,没有任何JavaScript。

#7


0  

<FORM action="" method="get">
<P>
<LABEL for="brand">Brand: </LABEL>
          <INPUT type="text" id="brand"><BR>
<LABEL for="priceMin">Minimum Price: </LABEL>
          <INPUT type="text" id="priceMin"><BR>
</P>

#8


0  

use var urlString = window.location to get the url

使用var urlString = window.location来获取url

check if the url already contains a '?' with urlString.indexOf('?'), -1 means it doesnt exist.

检查网址是否已包含“?”使用urlString.indexOf('?'),-1表示它不存在。

set window.location to redirect

将window.location设置为重定向

this is like 101 of javascript. try some search engines!

这就像是javascript的101。尝试一些搜索引擎!

#9


0  

<html>
<body>
..
..
..

<?php
$priceMinValue= addslashes ( $_GET['priceMin']);
if (!empty($priceMin)) {
        $link = "currentpage.php?priceMin=". $priceMinValue;
        die("<script>location.href = '".$link. "'</script>");    
}
?>
</body>
</html>