I am sending an Array of values through Ajax via jQuery with a Play Framework backend, and I'm in front of a problem.
Here's an example :
$.ajax ({
'type': 'POST',
'url': '/url',
'timeout': 5000,
'data': {'ids': [0, 1, 2, 3]},
'dataType': 'json',
'success': function (oData) {
// Process ...
}
});
But in Play!, if I do a params.get("ids");, I got an empty value, and if I do a params.getAll("ids"); also.
I know where the problem is, jQuery send the data as : ids[]=0&ids[]=1&ids[]=2&ids[]=3
but Play! Framework expect array data to be sent as ids=0&ids=1&ids=2&ids=3
Is there a proper way to send the data properly (or get the data as an array in my controller) ?
So far, I managed to make it works simply but creating the request as a String manually in JavaScript.
One method (leaving your JavaScript code intact) is just declaring your controller method like this:
public static void myMethod(@As("ids[]:")List<Long> ids) {
System.out.println(ids.get(0));
}
.. the output is what you expect:
[0, 1, 2, 3]
I'm not sure if there's an easier way, but you could just send a string and decode that using GSON, i.e:
$.ajax ({
'type': 'POST',
'url': '/url',
'timeout': 5000,
'data': {'ids': '[0, 1, 2, 3]'},
'dataType': 'json',
'success': function (oData) {
// Process ...
}
});
Within your controller, you can convert the string into an array:
// data would be "[0, 1, 2, 3]"
int[] intArray = gson.fromJson(data, int[].class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With