jqueryajaxarraysplayframework

Play Framework and jQuery Ajax request with data as Array


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.

Thanks for your help.


Solution

  • 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]