Javascript 如何在 URL 中添加参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6899097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a parameter to the URL?
提问by Sumit Gupta
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)时,我希望我的 URL 变为
http://something.com/mobiles.php?brand=samsung&priceMin=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
回答by petho
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, "" + 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);
回答by hakre
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.
无需检查,?
因为这已经是search
零件,您只需要添加参数。
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.
请记住,这完全符合您的要求:添加该特定参数。它可以已经是部件的search
一部分,因为您可以在一个 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
:
由于search
已经提供了搜索字符串,唯一需要实现的是将该查询信息部分解析为名称和值对,更改或添加缺少的名称和值,然后将其添加回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 标签,这可能会失败。
回答by pimvdb
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
这种方式进行,但这应该无关紧要)。
回答by Leon Bauer
I rewrite the correctanswer 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, "" . $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...
我希望有人帮助...
回答by Martin
var applyMinPrice = function(minPrice) {
var existingParams = (location.href.indexOf('?') !== -1),
separator = existingParams ? '&' : '?',
newParams = separator + 'priceMin=' + minPrice;
location.href += newParams;
}
回答by Suresh
<html>
<body>
..
..
..
<?php
$priceMinValue= addslashes ( $_GET['priceMin']);
if (!empty($priceMin)) {
$link = "currentpage.php?priceMin=". $priceMinValue;
die("<script>location.href = '".$link. "'</script>");
}
?>
</body>
</html>
回答by bjelleklang
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。
回答by zeal
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.
检查 url 是否已经包含一个 '?' 用urlString.indexOf('?')
,-1表示它不存在。
set window.location
to redirect
设置window.location
为重定向
this is like 101 of javascript. try some search engines!
这就像 101 的 javascript。尝试一些搜索引擎!
回答by Sherif elKhatib
<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>