Send an array via a GET request using AngularJS '$ http service

I need to send a GET request using the $http service. One of the parameters will be an array of identifiers. The URL looks like this: mysite.com/items?id [] = 1 & id [] = 2 & id [] = 3 & id [] = 4

I tried this approach

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

but url i obain - mysite.com/items?id=%5B%221%22%2C%222%22%2C%223%22%2C%224%22%5D

This is because Angular converts my value to a JSON string. Is there a way to get the behavior I want?

[Update]

I solved the problem thanks to Jonathan's suggestion using jQuery $.param() .

 $http( method: 'GET' url: '/items?' + $.param({id: ids}) ) 
+47
javascript angularjs
Nov 13 '13 at 15:32
source share
7 answers
 $http( method: 'GET', url: '/items', params: { id: JSON.stringify(ids) // ids is [1, 2, 3, 4] } ) 
+58
Jan 22 '14 at 15:31
source

You can also just do

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

as mentioned here . It seems easier.

+70
Sep 18 '14 at 19:41
source

jQuery is great, but if you add jQuery just for that, you can probably do it using a non jQuery method and save precious bytes.

Non jQuery method:

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

On the 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 } 
+10
Mar 29 '14 at 17:20
source

It really, just decrypt it on your server. Almost all backend languages ​​have a URI decoding method. If you don't like the way Angular is serialized, you can try jquery $ .param ().

+5
Nov 13 '13 at 15:40
source

you can use $ httpParamSerializer or $ httpParamSerializerJQLike

 $http({ method: 'GET', url: '/items', data: $httpParamSerializer({'id':[1,2,3,4]}), }) 
+1
Jul 12 '16 at 7:19
source

The paramSerializer parameter can be set to replicate the jQuery serialization method :

 $http({ url: myUrl, method: 'GET', params: myParams, paramSerializer: '$httpParamSerializerJQLike' }); 
+1
Sep 08 '16 at 13:13
source

As long as you have too many identifiers, 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) { } 
0
Jul 16 '16 at 15:23
source



All Articles