Passing array through AJAX (Grails)

Despite many resources online, I had a very hard timing figuring out how to pass an array from a view (GSP) to controller action. Here is a brief write-up on how I accomplished this, after lots of trial-and-error:

In the view:
Create an object called params with an attribute that is an array (along with whatever other values you want)

var params = new Object();
params.myArray = new Array();

Set the values within the array:

params.myArray[1] = 'blah';
params.myArray[2] = 'whatever';

Send the params object through AJAX using the “data” paramater in ajax:

$.ajax({
async: false,
url: 'controllerAction',
data:$.param(params),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
...
}
});

Then, in the controller, you can access the ‘params’ object and all of its attributes (including the array):

def controllerAction = {
System.out.println( params.'myArray[]'[1] )
System.out.println( params.'myArray[]'[2] )
}

So in this case, your output will be:
blah
whatever

Note that the name of the array element of your params object is ‘myArray[]’. This is the real tricky part of the whole thing and took me a long time to figure out.

Advertisements