Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem consuming JSON object in a servlet

This is what i'm trying to do and its pretty simple but i'm getting stuck: I'm trying to send a JSON object formed in JSP to a server side servlet and parse it .

What i've done till now:

  • Constructed the json.
  • sending the json to the backend
$.ajax({
            data: jsontosend,
            url: 'MYSERVLET?name=asdf',
            success: function(res){
                alert('posted');
            }
        })

Problem:

  • What name is this JSON refrenced by so i can get it in the servlet using the request.getParameter() ?
  • When i print request.getParameterNames() , i get the parameter name as the JSON string itself so the output of all parameter names inside the MYSERVLET looks like this
Parameter = name
Parameter = {"ticker":"asd","date":"asd","bucket":"300","entry":[{"type":"asd","indicator":"asd","condition":"asd"}],"exit":[{"type":"qwe","indicator":"qwe","condition":"qwe"}]}

Anyone have an idea as to what the problem is ?

Also i tried looking at this question here on stackoverflow but the same problem exists there too. Also there is a duplicate question which hasn't been answered .

Help! :(

like image 772
Shrayas Avatar asked Mar 04 '26 10:03

Shrayas


1 Answers

Read http://api.jquery.com/jQuery.ajax/#sending-data-to-server:

The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent.

So, you should use

$.ajax({
        data: {theNameOfTheParameter : jsontosend,
               name : 'asdf'},
        url: 'MYSERVLET',
        success: function(res){
            alert('posted');
        }
    })

and use request.getParameter("theNameOfTheParameter") to get the JSON string.

like image 101
JB Nizet Avatar answered Mar 05 '26 23:03

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!