0

I have some data that I need to send that is in a 2D array. I found that you send an array through post here here but i need to send a 2D array from my javascript using post to a java servlet. Is there a way to do this?

1 Answer 1

1

You can use exactly the same technique as the example you link to. This is because it uses JSON to serialise the data, so it can send entire JS data structures in one go. So, taking the example, but rebuilding it for a 2d array and tweaking it to send actual JSON:

var obj=[ [1.1, 1.2], [2.1, 2.2], [3.1, 3.2] ];
$.ajax({
        url:"myUrl",
        type:"POST",
        dataType:'json',
        success:function(data){
            // codes....
        },
        data:JSON.stringify(obj),
        contentType: 'application/json'
    });

Then this will send a string to your server, like:

"[[1.1,1.2],[2.1,2.2],[3.1,3.2]]"

Your Java servlet will then have to deserialise this and use it however you want. In this example, the JSON will be sent as RAW post data; if you want to get it via the request object, you can do something like:

var obj=[ [1.1, 1.2], [2.1, 2.2], [3.1, 3.2] ];
$.ajax({
        url:"myUrl",
        type:"POST",
        dataType:'json',
        success:function(data){
            // codes....
        },
        data: {json: JSON.stringify(obj)}
    });

Then you should be able to get the JSON string from:

request.getParameterValues("json");
Sign up to request clarification or add additional context in comments.

2 Comments

So how would i deserialise the 2d array into a 2d string array on my servlet side?
Check out the json.org site - json.org/java ... you'll need to pull the JSON string out of the raw POST data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.