admin管理员组文章数量:1128489
Is there any way to create the query parameters for doing a GET request in JavaScript?
Just like in Python you have urllib.urlencode()
, which takes in a dictionary (or list of two tuples) and creates a string like 'var1=value1&var2=value2'
.
Is there any way to create the query parameters for doing a GET request in JavaScript?
Just like in Python you have urllib.urlencode()
, which takes in a dictionary (or list of two tuples) and creates a string like 'var1=value1&var2=value2'
.
- 1 Reverse question: url - How can I get query string values in JavaScript? - Stack Overflow – user202729 Commented Nov 4, 2021 at 5:19
18 Answers
Reset to default 277URLSearchParams has increasing browser support.
const data = {
var1: 'value1',
var2: 'value2'
};
const searchParams = new URLSearchParams(data);
// searchParams.toString() === 'var1=value1&var2=value2'
Node.js offers the querystring module.
const querystring = require('querystring');
const data = {
var1: 'value1',
var2: 'value2'
};
const searchParams = querystring.stringify(data);
// searchParams === 'var1=value1&var2=value2'
Here you go:
function encodeQueryData(data) {
const ret = [];
for (let d in data)
ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
return ret.join('&');
}
Usage:
const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };
const querystring = encodeQueryData(data);
functional
function encodeData(data) {
return Object.keys(data).map(function(key) {
return [key, data[key]].map(encodeURIComponent).join("=");
}).join("&");
}
Zabba has provided in a comment on the currently accepted answer a suggestion that to me is the best solution: use jQuery.param().
If I use jQuery.param()
on the data in the original question, then the code is simply:
const params = jQuery.param({
var1: 'value',
var2: 'value'
});
The variable params
will be
"var1=value&var2=value"
For more complicated examples, inputs and outputs, see the jQuery.param() documentation.
The built-in URL
class provides a convenient interface for creating and parsing URLs.
There are no networking methods that require exactly a URL
object, strings are good enough. So technically we don’t have to use URL
. But sometimes it can be really helpful.
本文标签: urlHow to create query parameters in JavascriptStack Overflow
版权声明:本文标题:url - How to create query parameters in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736705122a1948634.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论