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

发布于 2024-11-05 20:19:25 字数 877 浏览 1 评论 0原文

我正在使用 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);

有人可以帮助我吗???

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

彩虹直至黑白 2024-11-12 20:19:25

您应该这样做:

服务器端:

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

希望这会有所帮助。干杯

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

嘦怹 2024-11-12 20:19:25

将它们包装在 JSON 数组中:

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

或者,将它们包装在另一个对象中:

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

Wrap them in JSON array:

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

or, wrap them in another object:

{ "result1":{..}, "result2":{..} }
风吹过旳痕迹 2024-11-12 20:19:25

您可以返回一个 JSON 数组,其中两个对象都作为数组的元素。让您的 servlet 返回具有如下结构的 JSON:

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

然后您的 javascript 代码可以是这样的:

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

    });

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

    });
长亭外,古道边 2024-11-12 20:19:25

你需要将它们放入一个 json 字符串中,这样

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

这会将它们放入一个 json 数组中,

你也可以将它们放入一个 json 对象中

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

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("}");
洋洋洒洒 2024-11-12 20:19:25

@Edgar 的答案对我有用。但我认为我们应该避免自己组成数组,所以我建议使用列表。代码将是这样的:

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

在前端,对于我们获取的数据,我们可以使用 data[0] 来检索 obj1data[ 1] 检索 obj2。代码将是这样的(我在这里使用ajax):

$('#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);
        }
    });
});

@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);
        }
    });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文