简体   繁体   中英

Pass POST Parameters with Jquery POST to Javascript from Java Servlet

From my JS I am starting a POST Request on my Servlet

$.post("RecipeServlet",
{
    r_id: r_id,
},
function(data, status){
    var foo =data.foo
    var bar =data.bar
});

And my Servlet is now supposed to do something with the r_id and should now pass results to my JS, since I need to pass Arrays aswell as simple Strings I thought I would need JSON and do it kinda like this:

response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.print(new Gson().toJson(bar));
    out.print(new Gson().toJson(foo));

How can I access the data correctly? I would like to access it like "data.bar" as you can see in the example JS. So my main question is probably, how do I manage to make the JSON Objects accessable by something like data.foo?

You need to specify the data type by adding it at the end of the $.post()

Example:

$.post( "RecipeServlet", { r_id: r_id }, function( data ) {
  var foo = data.foo
  var bar = data.bar
}, "json");

Source: http://api.jquery.com/jquery.post/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM