50

我需要使用该$http服务发送一个 GET 请求。其中一个参数将是一个 id 数组。网址看起来像这个mysite.com/items?id[]=1&id[]=2&id[]=3&id[]=4

我试过这种方法

$http(
  method: 'GET',
  url: '/items',
  params: {
    id: ids // ids is [1, 2, 3, 4]
  }
)

但我获得的网址是mysite.com/items?id=%5B%221%22%2C%222%22%2C%223%22%2C%224%22%5D

那是因为 Angular 正在将我的值转换为 JSON 字符串。有没有办法得到我想要的行为?

[更新]

由于 Jonathan 建议使用 jQuery 的$.param().

$http(
  method: 'GET'
  url: '/items?' + $.param({id: ids})
)
4

7 回答 7

78

你也可以这样做

$http(
  method: 'GET',
  url: '/items',
  params: {
    "id[]": ids // ids is [1, 2, 3, 4]
  }
)

正如这里提到的。看起来更简单。

于 2014-09-18T19:41:09.680 回答
62
$http(
  method: 'GET',
  url: '/items',
  params: {
    id: JSON.stringify(ids) // ids is [1, 2, 3, 4]
  }
)
于 2014-01-22T15:31:15.950 回答
10

jQuery 很棒,但如果您只是为此添加 jQuery,那么您可能会使用非 jQuery 方式并节省一些宝贵的字节。

非jQuery方式:

$http(
  method: 'GET',
  url: '/items',
  params: {
    id: ids.toString() //convert array into comma separated values
  }
)

在您的服务器上将其转换回数组。

例如。在php中

$ids = explode(',',Input::get('ids'));

//now you can loop through the data like you would through a regular array. 

foreach($ids as $id)
{
 //do something
}
于 2014-03-29T17:20:30.577 回答
5

这是有效的,只需在您的后端对其进行解码。几乎所有后端语言都有解码 URI 的方法。如果你不喜欢 Angular 序列化它的方式,你可以试试 jquery 的 $.param()。

于 2013-11-13T15:40:59.460 回答
1

你可以使用 $httpParamSerializer 或 $httpParamSerializerJQLike

$http({
  method: 'GET',
  url: '/items',
  data: $httpParamSerializer({'id':[1,2,3,4]}),
})
于 2016-07-12T07:19:42.797 回答
1

paramSerializer 选项可以设置为复制 jQuery 的序列化方法

$http({
  url: myUrl,
  method: 'GET',
  params: myParams,
  paramSerializer: '$httpParamSerializerJQLike'
});
于 2016-09-08T13:13:26.883 回答
0

只要您没有太多的 id,这会导致您的请求 url 太长,具体取决于您的配置,以下解决方案将起作用...

角服务:

$http.get("website.com/api/items?ids=1&ids=2&ids=3");

WebApi 控制器

[HttpGet, Route("api/items")]
public IEnumerable<Item> Get([FromUri] string[] ids)
{
}
于 2016-07-16T15:23:54.893 回答