Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return multiple json objects from java servlet using one ajax request

I am building web application using jsp and servlet, I send ajax request from jsp and I want to return two json objects from servlet. I tried to do the following but the code did not work.

// in jquery I wrote this code

        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"]);

        });

// in the servlet I wrote this code

    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);

can someone help me???

like image 413
sahar Avatar asked May 07 '11 19:05

sahar


People also ask

How do I combine multiple JSON objects into one?

JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java. util.

Can a JSON file have multiple JSON objects?

The file is invalid if it contains more than one JSON object. When you try to load and parse a JSON file with multiple JSON objects, each line contains valid JSON, but as a whole, it is not a valid JSON as there is no top-level list or object definition.

Can you have multiple JSON objects?

Can JSON have multiple objects? You can pass a single JSON object to create a single element, or a JSON array of group JSON objects to create multiple elements.


2 Answers

You should do it like this:

Server side:

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);

Client side:

$.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"]);
});

Hope this helps. Cheers

like image 162
Edgar Villegas Alvarado Avatar answered Nov 15 '22 19:11

Edgar Villegas Alvarado


Wrap them in JSON array:

[ {..}, {..}, {..}]

or, wrap them in another object:

{ "result1":{..}, "result2":{..} }
like image 20
Peter Knego Avatar answered Nov 15 '22 19:11

Peter Knego