通过Jquery POST从Java Servlet传递POST参数到Javascript

Pass POST Parameters with Jquery POST to Javascript from Java Servlet

本文关键字:POST 参数 传递 Javascript Java Jquery 通过 Servlet      更新时间:2023-09-26

从我的JS我开始一个POST请求我的Servlet

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

我的Servlet现在应该与r_id做一些事情,现在应该将结果传递给我的JS,因为我需要传递数组以及简单的字符串,我认为我需要JSON,这样做:

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

如何正确访问数据?我想像访问"数据"一样访问它。你可以在JS示例中看到。我的主要问题是,如何让JSON对象可以通过data。foo访问?

您需要通过在$.post()

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

的例子:

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

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