Send array via GET request with AngularJS' $http service

帅比萌擦擦* 提交于 2019-11-28 05:40:45
$http(
  method: 'GET',
  url: '/items',
  params: {
    id: JSON.stringify(ids) // ids is [1, 2, 3, 4]
  }
)

You can also just do

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

as mentioned here. Seems simpler.

jQuery is great but if your adding jQuery just for this then you could probably do with a non jQuery way and save some precious bytes.

Non jQuery way :

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

On your server convert it back to an array.

Eg. in 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
}

This is valid, just decode it on your backend. Almost all backend languages have a way to decode a URI. If you don't like the way that Angular is serializing it, you can try jquery's $.param().

The paramSerializer option can be set to replicate jQuery's serialization method:

$http({
  url: myUrl,
  method: 'GET',
  params: myParams,
  paramSerializer: '$httpParamSerializerJQLike'
});
Ben Hsieh

you can use $httpParamSerializer or $httpParamSerializerJQLike

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

As long as you don't have too many ids, which will cause your request url to be too long depending on your configuration, the following solution will work...

Angular Service:

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

WebApi Controller

[HttpGet, Route("api/items")]
public IEnumerable<Item> Get([FromUri] string[] ids)
{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!