从参数对象构建查询字符串 [英] Build query string from parameters object
问题描述
如何在Angularjs中使用查询参数构建网址。
How to build a url with query parameters in Angularjs.
我看到了API $ location.search()
问题是$ location(url)是重定向到网址。在我的例子中,我想为查询参数传递url和key:value对并构建url。类似
the problem is $location(url) is to redirect to the url. In my case, I want to pass a url and key:value pairs for the query params and build the url. something like
url: / a / b / c
params: {field1:value1,field2:value2}
结果: / a / b / c?field1 = value1& field2 = value2
我喜欢使用此网址作为链接。我还看到了角度编码?
,&
字符。我可以避免这种情况吗?
I like to use this url for links. I have also seen angular encode ?
, &
characters. Can I avoid this?
我的意图是使用url作为锚元素的href。我确实使用$ http发送请求,但有时我需要提供一个链接,带有查询参数(基于当前对象)
My intention was to use the url as href for anchor elements. I do use $http to send the request, but sometimes I need to provide a link, with query params (based on the current object)
谢谢
推荐答案
从1.4+开始,有一个很好的解决方案。您可以使用 $ httpParamSerializer
从参数对象构建查询字符串:
There is a nice solution as of 1.4+. You can build a query string from a parameters object with $httpParamSerializer
:
var qs = $httpParamSerializer(params);
默认$ http params序列化程序,根据以下内容将对象转换为字符串
遵循以下规则:
Default $http params serializer that converts objects to strings according to the following rules:
{'foo': 'bar'} results in foo=bar
{'foo': Date.now()} results in foo=2015-04-01T09%3A50%3A49.262Z (toISOString() and encoded representation of a Date object)
{'foo': ['bar', 'baz']} results in foo=bar&foo=baz (repeated key for each array element)
{'foo': {'bar':'baz'}} results in foo=%7B%22bar%22%3A%22baz%22%7D" (stringified and encoded representation of an object)
Note that serializer will sort the request parameters alphabetically.
这篇关于从参数对象构建查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!