使用通过ajax返回的java字符串填充谷歌PIE图表

时间:2014-09-10 09:50:38

标签: java javascript ajax google-visualization

我第一次使用此Google图表,因此我会请求您帮助我解决以下问题。

我使用两个图表:条形图和饼图。如果我单击条形图中的特定列,则应在同一屏幕中加载相应的饼图,使用ajax调用填充饼图的值。问题是我以javascript arraylist的形式返回一个字符串。我可以看到返回的字符串格式正确,但我得到了Uncaught Error : Not an Array

我使用google.visualization.arrayToDataTable()方法生成饼图。请提供宝贵的帮助以解决此问题。代码如下。

JSP Code:
*********
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Incident Entry</title>
<link href="css/style_strauto.css" type="text/css" rel="stylesheet" />
<link href='css/ui-lightness/jquery-ui.min.css' type="text/css"
    rel="stylesheet" />
<link href='css/warning_style.css' type="text/css" rel="stylesheet" />
<link href='css/timePicker.css' type="text/css" rel="stylesheet" />
<script type="text/javascript"
    src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<script type="text/javascript"
    src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", {
        packages : [ "corechart" ]
    });
    var barChart;
    var piChart;
    google.setOnLoadCallback(drawChart);
    var barData = google.visualization
            .arrayToDataTable([ <c:out value="${incidentArray}" escapeXml="false" /> ]);
        var piData = google.visualization
            .arrayToDataTable(<c:out value="${piChatArray}" escapeXml="false" />);  
    function drawChart() {

        var barView = new google.visualization.DataView(barData);
        barView.setColumns([ 0, 1, {
            calc : "stringify",
            sourceColumn : 1,
            type : "string",
            role : "annotation"
        }, 2 ]);

        var barOptions = {
            title : "Top 10 CI's with High Incidents",
            width : 500,
            height : 350,
            bar : {
                groupWidth : "95%"
            },
            legend : {
                position : "none"
            },
            is3D : true
        };

        var piOptions = {
            width : 500,
            height : 350,
            title : 'Detail Analysis of CI\'s',
            is3D : true
        };

        var piChart = new google.visualization.PieChart(document
                .getElementById('piechart'));
        barChart = new google.visualization.ColumnChart(document
                .getElementById("columnchart_values"));
        piChart.draw(piData, piOptions);
        barChart.draw(barView, barOptions);
        google.visualization.events.addListener(barChart, 'select',
                myClickHandler);

        function myClickHandler(e) {

            var row = "";
            var column = "";
            var selection = barChart.getSelection();

            for (var i = 0; i < selection.length; i++) {
                var item = selection[i];
                if (item.row != null && item.column != null) {
                    row = item.row;
                    column = item.column;
                } else if (item.row != null) {
                    row = item.row;
                } else if (item.column != null) {
                    column = item.column;
                }
            }
             makeServerAjaxCall(row,column);
            //var piArrayList =$('#result').text();
            var piArrayList = [["Incidents","Percentage"],["Resolver Self-Creation",38],];
            //var res = piArrayList.split("|");
            alert(piArrayList);
            piData = google.visualization.arrayToDataTable(piArrayList);
            drawChart(); 
        }
    }

    function makeServerAjaxCall(row, column) {
        var returnVal;
        $.ajax({
            type : 'GET', // Or any other HTTP Verb (Method)
            url : 'incident_managment_pichart.htm',
            data : {
                rowVal : row,
                colVal : column
            },
            async : false,
            // async * false = !async = sync
            success : function(responseText) {
            //alert($.parseJSON(responseText));
             $("#result").html(responseText);
                returnVal = $("#result").html(responseText);

            },
            error : function(e) {
                alert("An error occured: " + e.status + " " + e.statusText);
                returnVal = '';
            }
        });

        return returnVal;
    }

    //Ajax Call for getting PI Chart Data

    //
</script>
<style>
table {
    font-family: arial, helvetica;
    font-size: 10pt;
    cursor: default;
    margin: 0;
    background: rgb(252, 248, 248);
    border-spacing: 0;
    color: black;
}
</style>
</head>
<body>
    <form:form id="barChartForm" method="GET"
        action="incident_managment_pichart.htm">
        <!-- Header Start -->
        <div id="hd">
            <div class="inner">
                <a class="logo" href="#">Logo</a>
                <h1 class="appName">Incident Report</h1>

            </div>
        </div>
        <!-- Header End -->

        <!-- Nav Start -->
        <div id="nav">
            <div class="inner">
                <div class="userProfile">
                    <img src="images/icoProfile.png" alt="User" /> <span><spring:message
                            code="capone.ito.dashboard.common.header.label.analyser" /></span>
                </div>
                <div class="links">
                    <a href="dashBoardHome.htm"> <spring:message
                            code="capone.ito.dashboard.common.header.label.home" />
                    </a>
                </div>
                <div class="menu">
                    <a href="##"><spring:message
                            code="capone.ito.dashboard.common.menu.label.dailyBoard" /></a> | <a
                        href="##"><spring:message
                            code="capone.ito.dashboard.common.menu.label.weeklyBoard" /></a> | <a
                        href="##"><spring:message
                            code="capone.ito.dashboard.common.menu.label.monthlyBoard" /></a> |
                    <a href="##"><spring:message
                            code="capone.ito.dashboard.common.menu.label.notification" /></a> |
                    <a href="##"><spring:message
                            code="capone.ito.dashboard.common.menu.label.upload" /></a>
                </div>
            </div>
        </div>
        <div style="margin-bottom: -20px;" id="bgnone" class="inner bdBGHome">
            <div class="clearboth ">
                <table>
                    <tr>
                        <td><div id="columnchart_values"
                                style="width: 475px; height: 350px;"></div></td>
                        <td><div id="piechart" style="width: 475px; height: 350px;"></div>
                        <div id="result"></div></td>
                </table>


            </div>
        </div>
    </form:form>
    <!-- Footer Start -->
    <div id="ft" class="inner">
        <span class="copyrights"></span>
    </div>
    <!-- Footer End -->
</body>
</html>

Response from AJAX:
******************
[["Incidents","Percentage"],["Resolver Self-Creation",38],]

AJAX Method call
*****************
public String doGeneratePIChart(ModelMap model, @RequestParam String rowVal,@RequestParam String colVal, HttpServletRequest request,
                  HttpServletResponse response) throws NumberFormatException, Exception
      {

            logger.debug("[IncidentManagementController doGeneratePIChart] : start");
            String piArray;
            List<PIChartVO> piChartVOList = new ArrayList<PIChartVO>();
            int row = Integer.valueOf(rowVal);
            IncidentRequestVO incidentVO = new IncidentRequestVO();// (IncidentRequestVO)
            // model.get("incidentRequestVO");
                  piChartVOList = incidentManageBO.getPIChartVO("ENVITOWINTELPROD");
            logger.debug("[IncidentManagementController : doGeneratePIChart] Array length :" + piChartVOList.size());
            piArray = toPIJavascriptArray(piChartVOList);
            logger.debug("[IncidentManagementController : doGeneratePIChart] Array String using internal -" + piArray);
            incidentVO.setPiChartList(piArray);
            logger.debug("[IncidentManagementController : doGeneratePIChart] row, column values :" + rowVal + "," + colVal);

            try {
                    response.getWriter().write(piArray);
                } catch (IOException e) {
                    logger.error("Error occure while retriving the server Details value " + e);     }
                return null;
}

1 个答案:

答案 0 :(得分:0)

我解决了使用下面的代码并删除了来自AJAX的响应中显示的额外“,”

        var piArrayList = makeServerAjaxCall(row,column);
        var obj = $.parseJSON(piArrayList);
        piData = google.visualization.arrayToDataTable(obj);
        drawChart(); 

感谢您的帮助: - )