gpt4 book ai didi

java - 如何从 .ajax 调用返回两个 JSON 数组?

转载 作者:行者123 更新时间:2023-11-29 06:41:27 25 4
gpt4 key购买 nike

我正在使用 jqPlot,因为我找不到一个合适的地方来了解如何通过 JSON 将多个系列发送到 jqplot,我将尝试解决它。​​

这里有一些背景知识:

现在,我可以调用我的 servlet 并返回一个 JSON 数组,其中包含我要在图表中显示的数据。

AJAX 调用

$.ajax({
type: 'POST',
cache: 'false',
data: params,
url: '/miloWeb/PlotChartServlet',
async: false,
dataType: 'json',
success: function(series){
coordinates = [series] ;
},
error: function (xhr, ajaxOptions, thrownError){
alert(ajaxOptions);
}
});

服务器

    private void generateCoordinates(HttpServletRequest request, HttpServletResponse response) throws IOException{

JSONArray coordinates = new JSONArray();
try {
coordinates = findChartCoordinatesByPatientPK();
} catch (JSONException e) {
e.printStackTrace();
}
response.getOutputStream().print(coordinates.toString());

}

这样做是返回字符串:

[["07/06/2000","22.0"],["08/06/2000","20.0"],["08/06/2003","15.0"],["08/06/2005","35.0"],["08/06/2007","12.0"],["08/06/2010","10.0"],["08/06/2012","10.0"]]

所以我将它存储在变量“坐标”中,并使用它们来绘制 jqPlot 图:

var plot10 = $.jqplot ('chartdiv', coordinates);

到目前为止一切正常,现在是我想要实现的目标:

如果我硬编码一个字符串来表示另一个数组中的两个数组,如下所示:

[[["07/06/2000","22.0"],["08/06/2000","20.0"],["08/06/2003","15.0"],["08/06/2005","35.0"],["08/06/2007","12.0"],["08/06/2010","10.0"],["08/06/2012","10.0"]], [["07/06/2000","21.0"],["08/06/2000","19.0"],["08/06/2003","14.0"],["08/06/2005","34.0"],["08/06/2007","11.0"],["08/06/2010","9.0"],["08/06/2012","9.0"]]]

我可以让 jQplot 在图表中绘制两条不同的线!所以我尝试做同样的事情,并通过 servlet 返回一个与那个字符串完全相同的字符串:

不工作的 SERVLET

    private void generateCoordinates(HttpServletRequest request, HttpServletResponse response) throws IOException{
JSONArray coordinates = new JSONArray();
JSONArray coordinates2 = new JSONArray();
try {
coordinates = VitalsBB.findChartCoordinatesByPatientPK();
coordinates2 = VitalsBB.findChartCoordinatesByPatientPK2();
} catch (JSONException e) {
e.printStackTrace();
}
response.getOutputStream().print( coordinates.toString() + ", " + coordinates2.toString());

}

但这不起作用,它给了我一个解析错误。那么我需要修改 AJAX 调用吗?或者有没有办法将两个 JSON arrays.toString() 返回到我的表单并将它们存储在一个变量中?或者我可能需要两个变量?

最佳答案

当您调用 response.getOutputStream().print() 时,您没有将两个子数组括在外部数组括号中。

试试这个:

response.getOutputStream().print("[" + coordinates.toString() + ", " + coordinates2.toString() + "]");

如果您的代码在您对数组进行硬编码时有效,那么这应该有效。

关于java - 如何从 .ajax 调用返回两个 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11441326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com