从参数对象构建查询字符串 [英] Build query string from parameters object

查看:28
本文介绍了从参数对象构建查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆