在Google图表中提供按钮和下拉列表

时间:2017-03-24 06:05:30

标签: javascript java jquery jsp

我在我的应用程序中嵌入了Google Charts,它在UI端显示如下图像:

enter image description here

还会显示下拉列表,如下图所示:

enter image description here

我在图表中添加了一个链接和一个按钮作为"导出"和"表数据"在上面的图像中看到。内部"出口"我提供了一个下拉列表。在其他图表中我只能得到"导出"仅链接,也无法获得下拉列表。

为了嵌入各种图表,我为每个图表使用了单独的JSP文件,就像我嵌入了列条形图和饼图,然后我为这两个图表创建了不同的JSP文件。

为了开发这个,我使用了2个JSP文件,一个是dashboardLayout.jsp,对于我使用foreach循环的嵌入式各种图表。 代码段如下:

dashboardLayout.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 <style>
    button {
        color:#fff;
        background-image: linear-gradient(to bottom,#337ab7 0,#265a88 100%);
        padding: 5px 10px;
        font-size: px;
        line-height: 1.5;
        border-radius: 3px;
        cursor: pointer;
        border-color: #265a88;
        text-shadow: 0 -1px 0 rgba(0,0,0,.2);
        box-shadow: inset 0 1px 0 rgba(255,255,255,.15),0 1px 1px rgba(0,0,0,.075);
    }
    button:hover{
        background-image: linear-gradient(to top,#337ab7 0,#265a88 100%);
        box-shadow: inset 0 1px 0 rgba(255,255,255,.25),0 1px 1px rgba(0,0,0,.175);
    } 
</style> 

<style>
    .click {
         background:none!important;
         border:none; 
         padding:0!important;
         font-family:Helvetica Neue,Helvetica,Arial,sans-serif; /*input has OS specific font-family*/
         color:#333;
         cursor:pointer;
    }
    .dropdown {
        position: relative;
        display: inline-block;
    }
    .dropdownhover {
        font-family: Helvetica Neue,Helvetica,Arial,sans-serif;
        font-size: 15px;
    }
    .dropdown-content {
        display: none;
        position: absolute;
        background-color: #666666;
        min-width: 160px;
        box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        z-index: 1;
    }

    .dropdown-content a {
        color: white;
        padding: 2px 2px; 
        text-align: left;
        text-decoration: none;
        display: block;
        font-family: Helvetica Neue,Helvetica,Arial,sans-serif;
    }

    .dropdown-content a:hover {background-color: #111111}

    .dropdown:hover .dropdown-content {
        display: block;
    }

    .dropdown:hover .dropbtn {
        background-color: #3e8e41;
    }
</style>

<script type="text/javascript">

    google.charts.load('current', {'packages':['corechart','table','timeline','charteditor']});

    $(document).ready(function() {

        $(".column").sortable({
                connectWith: ".column",
                handle: ".portlet-header",
                cancel: ".portlet-toggle",
                placeholder: "portlet-placeholder ui-corner-all",
                stop : function(event, ui) {

                    var currentDivId = this.id;
                    var parentDivId  = $(ui.item).parents().attr('id')

                    console.log('javascript ==>  currentDivId : '+currentDivId+", parentDivId : "+parentDivId);
                    if(currentDivId != parentDivId){
                        updateDashboardChartOrderAjaxFunction(currentDivId, parentDivId);  
                    } 
                } 
        }) 

        $(".portlet")
             .addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
             .find( ".portlet-header" )
             .addClass( "ui-widget-header ui-corner-all" )
             .prepend( "<span class='ui-icon ui-icon-minusthick portlet-toggle'></span>");

    });  

    function chartScrollBarHide(divId) {
        $('#'+divId).css("overflow-x", "hidden");
        $('#'+divId).css("margin-bottom", "48px");
    }
</script>

<c:forEach var="chart" items="${chartPropertiesList}" varStatus="theCount">

    <div class="column" id="${chart.merchantReportId}/${theCount.count}">
        <div class="portlet" id="${chart.chartHeaderTitle}"> 
            <div class="portlet-header">${chart.chartHeaderTitle}</div>

              <c:if test="${not empty chart.merchantReportData.responseData or not empty chart.merchantReportData.categoriesJsonData}">
                    <div style="text-align: center; padding: 5px 0px;" class="boson-font">
                         Change Chart : 
                         <select id="changeChart${theCount.count}" name="changeChart${theCount.count}" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif;font-size: 15px;" 
                                 onchange="changeChartAjaxFunction('${chart.merchantReportId}','${chart.chartDivId}',this.value);" >

                            <c:forEach var="chartType" items="${chartTypeNameList}">    
                                <c:choose>
                                    <c:when test="${chartType.key eq chart.chartName}">
                                        <option value="${chartType.key}" selected="selected">${chartType.value}</option>
                                    </c:when>
                                    <c:otherwise>
                                        <option value="${chartType.key}">${chartType.value}</option>                    
                                    </c:otherwise>
                                </c:choose>
                            </c:forEach>                                                                                                      
                        </select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <div class="dropdown">
                            <a href="#" class="dropdownhover">Export</a>
                                <div class="dropdown-content" id="export"></div>
                        </div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <a href="#" class="dropdownhover" id="tables"></a> 
                    </div>   
              </c:if>

               <c:choose>
                    <c:when test="${chart.chartName eq 'columnbar'}">
                         <jsp:include page="chartsview/columnBarChart.jsp">
                            <jsp:param name="chartDivId" value="${chart.chartDivId}"/>
                            <jsp:param name="jsondata" value="${chart.merchantReportData.responseData}"/>
                            <jsp:param name="linkedJsonData" value="${chart.merchantReportData.responseLinkedData}"/>
                            <jsp:param name="xaxisLable" value="${chart.xAxisLable}"/>
                            <jsp:param name="yaxisLable" value="${chart.yAxisLable}"/>
                         </jsp:include> 
                         <div class="portlet-content" id="${chart.chartDivId}"> ColumnBar Chart load here </div>
                    </c:when>

                    <c:when test="${chart.chartName eq 'pie'}">
                        <jsp:include page="chartsview/pieChart.jsp">
                            <jsp:param name="chartDivId" value="${chart.chartDivId}"/>
                            <jsp:param name="jsondata" value="${chart.merchantReportData.responseData}"/>
                            <jsp:param name="linkedJsonData" value="${chart.merchantReportData.responseLinkedData}"/>
                            <jsp:param name="xaxisLable" value="${chart.xAxisLable}"/>
                            <jsp:param name="yaxisLable" value="${chart.yAxisLable}"/>
                         </jsp:include>     
                         <div class="portlet-content" id="${chart.chartDivId}"> Pie Chart load here pie</div>
                    </c:when> 

                </c:choose>
            </div>
    </div>

    <c:if test="${empty chart.merchantReportData.responseData and empty chart.merchantReportData.categoriesJsonData}">
        <script type="text/javascript">
            chartScrollBarHide('${chart.chartDivId}');
        </script>
    </c:if>

</c:forEach>

columBarChart.jsp

    <script type="text/javascript">
google.charts.load('current', {'packages':['corechart','table','timeline','charteditor']});
    google.charts.setOnLoadCallback(drawChart);

    var chartDivId = null;
    var options = null;
    var data = null;
    var fileName = 'Test';

    function AddNamespaceHandler() {
        var svg = jQuery("#"+chartDivId+" svg");
        svg.attr("xmlns", "http://www.w3.org/2000/svg");
        svg.css('overflow','visible');
    }

    function drawChart() {
        var chartData = [
                         ['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Rwanda', 'Average'],
                         ['2004/05',  165,      938,         522,         450,      614.6],
                         ['2005/06',  135,      1120,        599,         288,      682],
                         ['2006/07',  157,      1167,        587,         397,      623],
                         ['2007/08',  139,      1110,        615,         215,      609.4],
                         ['2008/09',  136,      691,         629,         366,      569.6]
                      ];

        chartDivId = "${param.chartDivId}";
        //chartDivId="17Div2";
        if(!chartDivId){
            chartDivId = "${chartDivId}";
        }
        console.log("columnbar div id: " + chartDivId);
        var xaxisLable = "${param.xaxisLable}";
        if(!xaxisLable){
            xaxisLable = "${xaxisLable}";
        }

        var yaxisLable = "${param.yaxisLable}";
        if(!yaxisLable){
            yaxisLable = "${yaxisLable}";
        }

        data = google.visualization.arrayToDataTable(chartData);

        options = {
            title: 'Monthly Coffee Production by Country',
            hAxis: {title: xaxisLable},
            vAxis: {title: yaxisLable},
            width : "600",
            height : "300"
        };

        var chart = new google.visualization.ColumnChart(document.getElementById(chartDivId));

        google.visualization.events.addListener(chart, 'ready', AddNamespaceHandler);
        chart.draw(data, options);

        var exportsColumn="return xepOnline.Formatter.Format('"+chartDivId+"', {render:'download', mimeType:'application/pdf', filename:'"+fileName+"'})";
        //jQuery('#export').html('<a href="#" onclick="'+ exports +'">Export To PDF</a>');

        var exportsColumn1="return xepOnline.Formatter.Format('"+chartDivId+"', {render:'download', mimeType:'image/svg+xml', filename:'"+fileName+"'})";

        jQuery('#export').html('<a href="#" onclick="'+ exportsColumn +'">Export To PDF</a> <a href="#" onclick="'+ exportsColumn1 +'">Export To Image</a>');

        // Chart Table Data - Start
         jQuery('#tables').html('<button class="click" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif; box-shadow: 0 0 0 0;" data-toggle="modal" data-target="#openModal" onclick="loadExportChartTable();">Table Data</button>');

        var buttons="return xepOnline.Formatter.Format('parent_table', {render:'download',mimeType:'application/pdf', filename:'"+fileName+"'})";

        jQuery('#buttons_table').html('<button onclick="'+ buttons +'">PDF</button> &nbsp;&nbsp;&nbsp; <button onclick="dataTableToCSV();">EXCEL</button>');

        /* jQuery('#buttons_table').append("&nbsp;&nbsp;&nbsp;");

        jQuery('#buttons_table').append('<button onclick="dataTableToCSV();">EXCEL</button>'); */
        // Chart Table Data - End
    }

    // Load the Export Chart table data
    function loadExportChartTable() {
        var table_data = new google.visualization.Table(document.getElementById('table_div'));

        google.visualization.events.addListener(table_data, 'ready', AddNamespaceHandler);
        table_data.draw(data, {showRowNumber: false, width: '100%', height: '100%'});
    }

    function dataTableToCSV() {

        var dataTable_arg = data;

        var dt_cols = dataTable_arg.getNumberOfColumns();
        var dt_rows = dataTable_arg.getNumberOfRows();

        var csv_cols = [];
        var csv_out;

        for (var i=0; i<dt_cols; i++) {
            csv_cols.push(dataTable_arg.getColumnLabel(i).replace(/,/g,""));
        }

        csv_out = csv_cols.join(",")+"\r\n";

        for (i=0; i<dt_rows; i++) {

            var raw_col = [];
            for (var j=0; j<dt_cols; j++) {
                raw_col.push(dataTable_arg.getFormattedValue(i, j, 'label').replace(/,/g,""));
            }

            csv_out += raw_col.join(",")+"\r\n";
        }

        //return csv_out;
        this.downloadCSV(csv_out, fileName);
    }

    function downloadCSV (csv_out, fileName) {

        var blob = new Blob([csv_out], {type: 'text/csv;charset=utf-8'});
        var url  = window.URL || window.webkitURL;
        var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
        link.href = url.createObjectURL(blob);
        link.download = fileName+".csv"; 

        var event = document.createEvent("MouseEvents");
        event.initEvent("click", true, true);
        link.dispatchEvent(event); 
    }
</script>

pieChart.jsp

    <script type="text/javascript">
google.charts.load('current', {'packages':['corechart','table','timeline','charteditor']});
    google.charts.setOnLoadCallback(drawChart);

    var chartDivId = null;
    var options = null;
    var data = null;
    var fileName = 'Test';

    function AddNamespaceHandler() {
        var svg = jQuery("#"+chartDivId+" svg");
        svg.attr("xmlns", "http://www.w3.org/2000/svg");
        svg.css('overflow','visible');
    }

    var chartData = [
                     ['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Rwanda', 'Average'],
                     ['2004/05',  165,      938,         522,         450,      614.6],
                     ['2005/06',  135,      1120,        599,         288,      682],
                     ['2006/07',  157,      1167,        587,         397,      623],
                     ['2007/08',  139,      1110,        615,         215,      609.4],
                     ['2008/09',  136,      691,         629,         366,      569.6]
                  ];

    function drawChart() {

        chartDivId = "${param.chartDivId}";
        if(!chartDivId){
            chartDivId = "${chartDivId}";
        }
        console.log("pieChart div id: " + chartDivId);
        var xaxisLable = "${param.xaxisLable}";
        if(!xaxisLable){
            xaxisLable = "${xaxisLable}";
        }

        var yaxisLable = "${param.yaxisLable}";
        if(!yaxisLable){
            yaxisLable = "${yaxisLable}";
        }

        var data = google.visualization.arrayToDataTable(chartData);

        var options = {
            title: 'Monthly Coffee Production by Country',
            hAxis: {title: xaxisLable},
            vAxis: {title: yaxisLable},
            width : "600",
            height : "300"
        };

        var chart = new google.visualization.PieChart(document.getElementById(chartDivId));

        google.visualization.events.addListener(chart, 'ready', AddNamespaceHandler);
        chart.draw(data, options);

        var exportsPie="return xepOnline.Formatter.Format('"+chartDivId+"', {render:'download', mimeType:'application/pdf', filename:'"+fileName+"'})";
        var exportsPie1="return xepOnline.Formatter.Format('"+chartDivId+"', {render:'download', mimeType:'image/svg+xml', filename:'"+fileName+"'})";

        jQuery('#export').html('<a href="#" onclick="'+ exportsPie +'">Export To PDF</a> <a href="#" onclick="'+ exportsPie1 +'">Export To Image</a>');

        // Chart Table Data - Start
         jQuery('#tables').html('<button class="click" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif; box-shadow: 0 0 0 0;" data-toggle="modal" data-target="#openModal" onclick="loadExportChartTable();">Table Data</button>');

        var buttons="return xepOnline.Formatter.Format('parent_table', {render:'download',mimeType:'application/pdf', filename:'"+fileName+"'})";

        jQuery('#buttons_table').html('<button onclick="'+ buttons +'">PDF</button> &nbsp;&nbsp;&nbsp; <button onclick="dataTableToCSV();">EXCEL</button>');
        // Chart Table Data - End
    }

    // Load the Export Chart table data
    function loadExportChartTable() {
        var table_data = new google.visualization.Table(document.getElementById('table_div'));

        google.visualization.events.addListener(table_data, 'ready', AddNamespaceHandler);
        table_data.draw(data, {showRowNumber: false, width: '100%', height: '100%'});
    }

    function dataTableToCSV() {

        var dataTable_arg = data;

        var dt_cols = dataTable_arg.getNumberOfColumns();
        var dt_rows = dataTable_arg.getNumberOfRows();

        var csv_cols = [];
        var csv_out;

        for (var i=0; i<dt_cols; i++) {
            csv_cols.push(dataTable_arg.getColumnLabel(i).replace(/,/g,""));
        }

        csv_out = csv_cols.join(",")+"\r\n";

        for (i=0; i<dt_rows; i++) {

            var raw_col = [];
            for (var j=0; j<dt_cols; j++) {
                raw_col.push(dataTable_arg.getFormattedValue(i, j, 'label').replace(/,/g,""));
            }

            csv_out += raw_col.join(",")+"\r\n";
        }

        //return csv_out;
        this.downloadCSV(csv_out, fileName);
    }

    function downloadCSV (csv_out, fileName) {

        var blob = new Blob([csv_out], {type: 'text/csv;charset=utf-8'});
        var url  = window.URL || window.webkitURL;
        var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
        link.href = url.createObjectURL(blob);
        link.download = fileName+".csv"; 

        var event = document.createEvent("MouseEvents");
        event.initEvent("click", true, true);
        link.dispatchEvent(event); 
    }
</script>

我需要相同的下拉菜单和&#34;表数据&#34;所有图表中的按钮现在只在第一张图表中显示。

如果有人有任何解决方案或想法来解决此问题。 请有人帮我搞定吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

最后我得到了回答我的问题。

下拉列表和表格数据按钮都接受静态ID,这就是为什么我只能在一个图表中获取的原因。

为了获得其他图表,我在dashboardLayout.jsp foreach循环中创建了动态添加计数变量,并在每个图表中的param变量中添加了在dashboardLayout.jsp文件中声明。

代码段如下:

dashboardLayout.jsp

    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            <div class="dropdown">
                                <a href="#" class="dropdownhover">Export</a>
                                    <div class="dropdown-content" id="export${theCount.count}"></div>
                            </div> 
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            <a href="#" class="dropdownhover" id="tables${theCount.count}"></a> 
 <c:choose>
                        <c:when test="${chart.chartName eq 'columnbar'}">
                             <jsp:include page="chartsview/columnBarChart.jsp">
                                <jsp:param name="chartDivId" value="${chart.chartDivId}"/>
                                <jsp:param name="jsondata" value="${chart.merchantReportData.responseData}"/>
                                <jsp:param name="linkedJsonData" value="${chart.merchantReportData.responseLinkedData}"/>
                                <jsp:param name="xaxisLable" value="${chart.xAxisLable}"/>
                                <jsp:param name="yaxisLable" value="${chart.yAxisLable}"/>
                                <jsp:param name="exportParam" value="export${theCount.count}"/>
                                <jsp:param name="tablesParam" value="tables${theCount.count}"/>
                             </jsp:include> 
                             <div class="portlet-content" id="${chart.chartDivId}"> ColumnBar Chart load here </div>
                        </c:when>
</c:choose>

columnBarChart.jsp

var exportDiv = null;
var tableDiv = null;

exportDiv = "${param.exportParam}";
    tableDiv = "${param.tablesParam}";

jQuery('#'+exportDiv).html('<a href="#" onclick="'+ exports1 +'">Export To PDF</a> <a href="#" onclick="'+ exports +'">Export To Image</a>');

 jQuery('#'+tableDiv).html('<button class="click" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif; box-shadow: 0 0 0 0;" data-toggle="modal" data-target="#openModal" onclick="loadExportChartTable();">Table Data</button>');