Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send request parameter array to servlet using jQuery $.ajax?

I would like to send JavaScript array to servlet using jQuery $.ajax.

var json=[1,2,3,4];
$.ajax({
            url:"myUrl",
            type:"POST",
            dataType:'json',
            success:function(data){
                // codes....
            },
            data:json

        });

When I use

request.getParameter("json");
request.getParameterValues("json");

It returns null.

How can I access the values?

like image 335
IbrahimAsad Avatar asked Nov 05 '12 22:11

IbrahimAsad


1 Answers

Send array as value of JS object so you end up as {json:[1,2,3,4]}.

var json=[1,2,3,4];
$.ajax({
    url:"myUrl",
    type:"POST",
    dataType:'json',
    data: {json:json},
    success:function(data){
        // codes....
    },
});

In servlet, you need to suffix the request parameter name with [].

String[] myJsonData = request.getParameterValues("json[]");

jQuery appends them in order to be friendly towards weak typed languages like PHP.

like image 59
Raunak Agarwal Avatar answered Oct 02 '22 15:10

Raunak Agarwal