只是想知道Javascript中是否有内置的东西可以接受表单并返回查询参数,例如:“var1=value&var2=value2&arr[]=foo&arr[]=bar…”

我已经想了很多年了。


当前回答

现在回答你的问题可能太迟了。 我有同样的问题,我不喜欢不断追加字符串创建URL。所以,我开始使用$。Param techhouse解释道。 我还找到了一个URI.js库,可以轻松地为您创建url。这里有几个例子可以帮助你: 这是其中之一:

var uri = new URI("?hello=world");
uri.setSearch("hello", "mars"); // returns the URI instance for chaining
// uri == "?hello=mars"

uri.setSearch({ foo: "bar", goodbye : ["world", "mars"] });
// uri == "?hello=mars&foo=bar&goodbye=world&goodbye=mars"

uri.setSearch("goodbye", "sun");
// uri == "?hello=mars&foo=bar&goodbye=sun"

// CAUTION: beware of arrays, the following are not quite the same
// If you're dealing with PHP, you probably want the latter…
uri.setSearch("foo", ["bar", "baz"]);
uri.setSearch("foo[]", ["bar", "baz"]);`

其他回答

Querystring可以提供帮助。

所以,你可以

const querystring = require('querystring')

url += '?' + querystring.stringify(parameters)

var 参数 = { 宽度:1680, 高度:1050 }; var str = jQuery.param( params ); console.log(str) <script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>

jQuery可以通过$.param来实现

$.param({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' })

// -> "action=ship&order_id=123&fees%5B%5D=f1&fees%5B%5D=f2&label=a+demo"

UrlSearchParams API是一个很好的建议,但我不敢相信没有人提到非常有用的.get和.set方法。它们可以用于操作查询字符串,不仅非常容易使用,还可以解决您可能遇到的许多问题。例如,在我的例子中,我想构建一个没有重复键的查询字符串。.set为您解决了这个问题。引用MDN文档:

URLSearchParams.set () 将与给定搜索参数关联的值设置为给定值。如果有多个值,则删除其他值。

示例(来自MDN):

let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search);

// Add a third parameter
params.set('baz', 3);

params.toString(); // "foo=1&bar=2&baz=3"

另一种更短的语法:

let url = new URL('https://example.com?foo=1&bar=2');

// Add a third parameter
url.searchParams.set('baz', 3);

url.searchParams.toString(); // "foo=1&bar=2&baz=3"

现在回答你的问题可能太迟了。 我有同样的问题,我不喜欢不断追加字符串创建URL。所以,我开始使用$。Param techhouse解释道。 我还找到了一个URI.js库,可以轻松地为您创建url。这里有几个例子可以帮助你: 这是其中之一:

var uri = new URI("?hello=world");
uri.setSearch("hello", "mars"); // returns the URI instance for chaining
// uri == "?hello=mars"

uri.setSearch({ foo: "bar", goodbye : ["world", "mars"] });
// uri == "?hello=mars&foo=bar&goodbye=world&goodbye=mars"

uri.setSearch("goodbye", "sun");
// uri == "?hello=mars&foo=bar&goodbye=sun"

// CAUTION: beware of arrays, the following are not quite the same
// If you're dealing with PHP, you probably want the latter…
uri.setSearch("foo", ["bar", "baz"]);
uri.setSearch("foo[]", ["bar", "baz"]);`