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

Myy*_*Myy 1 javascript java ajax json servlets

我正在使用jqPlot,因为我找不到一个像样的地方来了解如何通过JSON发送多个系列到jqplot,我会尝试解决它.

所以这里有一点背景:

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

AJAX CALL

$.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);
            }   
        });
Run Code Online (Sandbox Code Playgroud)

SERVLET

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

}
Run Code Online (Sandbox Code Playgroud)

这样做是返回字符串:

[[ "2000年7月6日", "22.0"],[ "2000年8月6日", "20.0"],[ "2003年8月6日", "15.0"],["2005年8月6日", "35.0"],[ "08/06/2007", "12.0"],[ "08/06/2010", "10.0"],[ "08/06/2012", "10.0"]]

所以我将它存储在变量'coordinates'中并使用它们绘制jqPlot图形:

var plot10 = $.jqplot ('chartdiv', coordinates);
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好,现在我想要实现的目标:

如果我硬编码一个String,它表示另一个数组中的两个数组,如下所示:

[[["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"]]]
Run Code Online (Sandbox Code Playgroud)

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

不工作的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());

    }
Run Code Online (Sandbox Code Playgroud)

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

pb2*_*b2q 7

调用时,不要将两个子数组括在外部数组括号中response.getOutputStream().print().

试试这个:

response.getOutputStream().print("[" + coordinates.toString() + ", " + coordinates2.toString() + "]");
Run Code Online (Sandbox Code Playgroud)

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