[英]What is the best way to compose a link with GET parameters using javascript or jquery
I want to compose a link with several GET parameters gathered from variables. 我想用从变量收集的几个GET参数组成一个链接。 For example:
例如:
link.php?param1=value1¶m2=value2¶m3=value3
In javascript, If I have variables var1, var2 and var3 set already to the corresponding values, I know the link can be composed by concatenating strings and the variables as follows: 在javascript中,如果我已经将变量var1,var2和var3设置为相应的值,则我知道可以通过串联字符串和变量来组成链接,如下所示:
url = "link.php?param1=" + var1 + "¶m2=" + var2 + "¶m3=" + var3;
Is there a cleaner or better way to do this? 有没有更清洁或更完善的方法来做到这一点? In jquery, the ajax requests function accept a data parameter that can be easily set as follows:
在jquery中,ajax请求函数接受一个数据参数,该参数可以轻松设置如下:
$.ajax({
url: url,
data:{
param1: var1,
param2: var2,
param3: var3
}
});
Is there a similar way to compose the link but simply store it inside a variable instead of performing an ajax request? 有没有类似的方法来组成链接,而只是将其存储在变量中而不执行ajax请求?
I'm aware of jquery's .get() function, which, as the documentation mentions: "Load data from the server using a HTTP GET request." 我知道jquery的.get()函数,正如文档中提到的那样:“使用HTTP GET请求从服务器加载数据。” I don't want this, I just need to compose the link.
我不要这个,我只需要组成链接。
var makeFullUrl = function (url, params) {
return [url, Object.keys(params || {}).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&')].join('?');
};
that's a function I made a while back (pre ES2015) - call it with the base URL as parameter 1, and an object like 这是我前一阵子(ES2015之前的版本)的功能-以基本网址作为参数1调用它,并使用如下对象
{
param1Name: param1Value,
param2Name: param2Value
}
Here it is for ES2015, for laffs
这是ES2015的
var makeFullUrl = (url, params) => [url, Object.keys(params || {}).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key])).join('&')].join('?');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.