HoosierCoder HoosierCoder -4 years ago 151
jQuery Question

How to serialize GET params with (jQuery Style) Nested Objects

I need to send in the following get request via Angular. Upon this request I have a rails server that takes in the param and returns JSON data.

GET request needed:


Angular code so far:

$http({method: 'GET', url: '/clients.json', params:{???}.success(function(data){
//angular does something

How would I send in the year parameters in Angular, so that the the server recognizes the c[year][2016] - nested array format? Basically, how would I properly replace the ??? in the code provided?

Answer Source

Use $httpParamSerializerJQLike:

var myUrl = '/clients.json'
var myParams = {c: {year: ["2015", "2016"]}};

  url: myUrl,
  method: 'GET',
  params: myParams,
  paramSerializer: '$httpParamSerializerJQLike'

The $httpParamSerializerJQLike service is the alternative $http params serializer that follows jQuery's param() method logic.

JSON:   {"c":{"year":[2014,2015]}}
Encode: c%5Byear%5D%5B%5D=2014&c%5Byear%5D%5B%5D=2015
Decode: c[year][]=2014&c[year][]=2015

The DEMO on JSFiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download