Pass POST Parameters with Jquery POST to Javascript from Java Servlet

时间:2015-05-24 22:15:31

标签: java javascript jquery json servlets

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?

1 个答案:

答案 0 :(得分:0)

您需要在 $。post()

的末尾添加数据类型来指定数据类型

示例:

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

来源:http://api.jquery.com/jquery.post/