如何使用一个ajax请求从java servlet返回多个json对象
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该这样做:
服务器端:
客户端:
希望这会有所帮助。干杯
You should do it like this:
Server side:
Client side:
Hope this helps. Cheers
将它们包装在 JSON 数组中:
或者,将它们包装在另一个对象中:
Wrap them in JSON array:
or, wrap them in another object:
您可以返回一个 JSON 数组,其中两个对象都作为数组的元素。让您的 servlet 返回具有如下结构的 JSON:
然后您的 javascript 代码可以是这样的:
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:
Then your javascript code can be something like this:
你需要将它们放入一个 json 字符串中,这样
这会将它们放入一个 json 数组中,
你也可以将它们放入一个 json 对象中
you're going to need to put both into a single json string like so
this puts them in a json array
you could also put them in a json object
@Edgar 的答案对我有用。但我认为我们应该避免自己组成数组,所以我建议使用列表。代码将是这样的:
在前端,对于我们获取的数据,我们可以使用
data[0]
来检索obj1
和data[ 1]
检索obj2
。代码将是这样的(我在这里使用ajax):@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:
And in the front end, for the data we get, we can use
data[0]
to retriveobj1
anddata[1]
to retriveobj2
. The codes will be something like this (I am using ajax here):