小编典典

如何使用一个ajax请求从java servlet返回多个json对象

java

我正在使用jsp和servlet构建Web应用程序,我从jsp发送ajax请求,我想从servlet返回两个json对象。我尝试执行以下操作,但是代码不起作用。

//在jquery中,我编写了这段代码

        var id = $(this).attr('id');

        var paramenters = {"param":id};

        $.getJSON("MyServlet", paramenters, function (data1,data2){

            $("h3#name").text(data1["name"]);

            $("span#level").text(data1["level"]);

            $("span#college").text(data2["college"]);

            $("span#department").text(data2["department"]);

        });

//在servlet中,我编写了此代码

    String json1 = new Gson().toJson(object1);

    String json2 = new Gson().toJson(object2);

    response.setContentType("application/json");

    response.setCharacterEncoding("utf-8");

    response.getWriter().write(json1);

    response.getWriter().write(json2);

有人能帮我吗???


阅读 330

收藏
2020-12-03

共1个答案

小编典典

您应该这样做:

服务器端:

String json1 = new Gson().toJson(object1); 
String json2 = new Gson().toJson(object2); 
response.setContentType("application/json"); 
response.setCharacterEncoding("utf-8"); 
String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
response.getWriter().write(bothJson);

客户端:

$.getJSON("MyServlet", paramenters, function (data){ 
   var data1=data[0], data2=data[1]; //We get both data1 and data2 from the array
   $("h3#name").text(data1["name"]); 
   $("span#level").text(data1["level"]); 
   $("span#college").text(data2["college"]); 
   $("span#department").text(data2["department"]);
});

希望这可以帮助。干杯

2020-12-03