3

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! :(

Community
  • 1
  • 1
Shrayas
  • 6,784
  • 11
  • 37
  • 54
  • Have you used something like Firefox's LiveHeaders to see what's being sent? You'll be able to see all of the key-value pairs being sent to the referring servlet. – El Guapo Sep 08 '11 at 13:55

2 Answers2

5

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

You don't get the json object in your servlet. JQuery transforms it into http parameters like what you get from a form. Example: ?ticker=asd&bucket=300

So to answer your question. There is no single name. The json objected is exploded t multiple names.

EDIT: try adding type: 'post'

for your request. You can also add processData: false in which case JQuery will send json and not http params. Anyway I really recommend using a http debugger like fiddler which will make it apperant what is being sent back and forth.

Esben Skov Pedersen
  • 4,437
  • 2
  • 32
  • 46