Reputation: 50097
This question seems to have the answer to what I am trying to do, but it does not seem to work for me. The servlet posts fine and in the watch window I can see my json object there for the _parameters
member variable of the servlet HttpRequest
, but I can't seem to get the parameter out.
Here is my code.
Javascript:
// build data from input fields
var jsondata = '{"author":"TEST", "title":"XYZ"}';
$.ajax({
type : 'POST',
dataType : 'json',
data: jsondata,
url : '/submitquote',
timeout : 5000,
success : function(data, textStatus) {
// whatever
},
error : function(xhr, textStatus, errorThrown) {
// whatever
}
});
Servlet (I also tried with "author" and "title" but nothing comes back):
// get data
String postData = req.getParameter("jsondata");
This is what I see using variable watch for _parameters
on the request object:
{{"author":"TEST", "title":"XYZ"}=}
How the heck do I get that stuff out?
Any help appreciated!
Upvotes: 1
Views: 5498
Reputation: 44376
First, the datatype
argument specifies the type of the data coming out, not the data going in.
Second, the data
argument should give a dictionary of parameters, and one of the parameters in this case is the already-stringified JSON object:
var jsondata = {"author":"TEST", "title":"XYZ"};
$.ajax({
type : 'POST',
dataType : 'json',
data: { jsondata : JSON.stringify(jsondata)},
url : '/submitquote',
timeout : 5000,
success : function(data, textStatus) {
// whatever
},
error : function(xhr, textStatus, errorThrown) {
// whatever
}
});
Now, req.getParameter("jsondata")
has the (still-JSON-stringified) data and you need to parse it yourself. JSON.org makes a very nice library you can use.
Two further notes:
data: {
and used in the getParameter
call.req.getParameter("author")
and req.getParameter("title")
.Upvotes: 4