从参数对象构建查询字符串 [英] Build query string from parameters object
问题描述
如何在 Angularjs 中使用查询参数构建 url.
How to build a url with query parameters in Angularjs.
我看到了 API $location.search()
问题是 $location(url) 是重定向到 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
网址:/a/b/c
参数:{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屋!