11

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???

5 Answers 5

23

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

Sign up to request clarification or add additional context in comments.

Comments

2

Wrap them in JSON array:

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

or, wrap them in another object:

{ "result1":{..}, "result2":{..} }

Comments

1

You could return a JSON array with both objects as elements of the array. Have your servlet return JSON that has a structure like this one:

[{"name": "object1"}, {"name": "object2"}]

Then your javascript code can be something like this:

$.getJSON("MyServlet", paramenters, function (data){
        var data1 = data[0];
        var data2 = data[1];

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

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

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

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

    });

Comments

1

you're going to need to put both into a single json string like so

response.getWriter().write("[");
response.getWriter().write(json1);
response.getWriter().write(",");
response.getWriter().write(json2);
response.getWriter().write("]");

this puts them in a json array

you could also put them in a json object

response.getWriter().write("{\"object1\":");
response.getWriter().write(json1);
response.getWriter().write(",\"object2\":");
response.getWriter().write(json2);
response.getWriter().write("}");

Comments

0

@Edgar 's answer works for me. But I think we should avoid to form the array by ourselves, so I suggest to use a list. The codes will be something like this:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ...
    resp.setContentType("application/json");
    resp.setCharacterEncoding("utf-8");
    ArrayList<Object> obj_arr = new ArrayList<Object>();
    obj_arr.add(obj1);
    obj_arr.add(obj2);
    Gson gson = new Gson();
    String tmp = gson.toJson(obj_arr);
    resp.getWriter().write(tmp);
}

And in the front end, for the data we get, we can use data[0] to retrive obj1 and data[1] to retrive obj2. The codes will be something like this (I am using ajax here):

$('#facts_form').submit(function (e) {
    e.preventDefault();
    var data = new FormData(this);
    var url = 'import';
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        processData: false,  
        contentType: false,   
        async: false,
        cache: false,
        success: function (data) {                
            for (var i = 1; i < data.length; i++){
               //do whatever 
            }
        },
        error: function (xhr, status, error) {
            alert(status + "\n" + error);
        }
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.