谷歌图表 - 通过按钮移动范围滑块控制导致错误

时间:2016-12-09 01:40:46

标签: javascript jquery ajax charts google-visualization

对于我的生活,我无法弄清楚为什么我遇到此问题,因为Google Chart错误消息中没有真正的提示。

问题

加载/显示图表后,点击任何按效果更改过滤按钮,Google图表显示错误消息

您使用错误的数据类型调用draw()方法而不是DataTable或DataView

这种情况似乎只发生在我使用ajax来填充表格行并且仅在绘制图表之后

JFiddle 不会表现出问题(没有ajax调用 - 静态行数据) https://jsfiddle.net/insatiabledev/owqkwvz7/23/

使用Ajax的JS代码在单击按功能更改过滤按钮时出现问题。返回与静态版本

中相同的行数据
/** Name Space global variables **/
reportingTableBarChart = {};

/** Google Visualization API DataTable Object **/
reportingTableBarChart.gvDataTable;

/** Google Visualization API Dashboard Object **/
reportingTableBarChart.gvDashboard;

/** Google Visualization API ChartWrapper Object **/
reportingTableBarChart.gvChartWrapper;

/** Google Visualization API Chart Filter Options **/
reportingTableBarChart.gvFilterPerformance;
reportingTableBarChart.gvFilterCatagory;
reportingTableBarChart.gvFilterDescription;
reportingTableBarChart.gvFilterUrl;

/** Table Chart Header **/
reportingTableBarChart.tableChartHeaders = [];

/** Database Data Results **/
reportingTableBarChart.databaseDataResults;


/**
 * Creates and draws report data table and bar chart elements using the Google Visualization API
 *
 * @param json
 *          JSON results from database
 *
 * @TODO COPY URL method
 */
reportingTableBarChart.createTableBarChart = function (urlQuery) {

    console.log("Google Visualization API Loaded");

    /** Get data for report from database and store it for later **/
    reportingTableBarChart.getReportData(urlQuery);

    /** Initialize Google Visualization API Objects **/
    reportingTableBarChart.gvDataTable = new google.visualization.DataTable();
    reportingTableBarChart.gvChartWrapper = new google.visualization.ChartWrapper();
    reportingTableBarChart.gvDashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));

    /** Get filter options for manipulating chart data **/
    reportingTableBarChart.getFilterPerformance();
    //reportingTableBarChart.getFilterCategory();
    //reportingTableBarChart.getFilterDescription();
    //reportingTableBarChart.getFilterUrl();

    /** Set ChartWrapper attributes **/
    reportingTableBarChart.gvChartWrapper.setChartType('BarChart');
    reportingTableBarChart.gvChartWrapper.setContainerId('tableChartContainer');
    reportingTableBarChart.gvChartWrapper.setOptions(reportingTableBarChart.getTableChartOptions());
    //reportingTableBarChart.gvChartWrapper.setViews(reportingTableBarChart.getTableChartView());

    /** Create chart columns **/
    reportingTableBarChart.getTableChartColumns();

    /** Add report data to chart **/
    reportingTableBarChart.gvDataTable.addRows(Object.values(reportingTableBarChart.databaseDataResults));

    console.log("ChartWrapper : " + reportingTableBarChart.gvChartWrapper.toJSON());
    console.log("DataTable : " + reportingTableBarChart.gvDataTable.toJSON());

    /** Add resize Listener to chart **/
    //reportingTableBarChart.addListenerTableChartHeightAutoResize();

    /** Add ability to click chart row item **/
    reportingTableBarChart.addListenerTableChartClickRow();

    /** Bind controls and chart to the Dashboard **/
    reportingTableBarChart.gvDashboard.bind( [
                                            reportingTableBarChart.gvFilterPerformance//,
                                            //reportingTableBarChart.gvFilterUrl,
                                            //reportingTableBarChart.gvFilterDescription,
                                            //reportingTableBarChart.gvFilterCatagory
                                              ],
                                              reportingTableBarChart.gvChartWrapper
                                            );

    /** Draw chart in the Dashboard **/
    reportingTableBarChart.gvDashboard.draw(reportingTableBarChart.gvDataTable);


    // detect when screen
    //autoResizeChart(reportingTableBarChart.gvChartWrapper, reportingTableBarChart.gvDataTable, reportingTableBarChart.getTableChartOptions);

    // apply default filter
    //reportingTableBarChart.setFilterPerformance(reportingTableBarChart.gvFilterPerformance);

    reportingTableBarChart.addListenerLoaded();
};



/**
 * JSON formatted Google Table Chart Options
 *
 * @returns json
 *          JSON formatted Google Table Chart Options
 */
reportingTableBarChart.getTableChartOptions = function () {

    /** Chart Table Options object **/
    var options = new Object();

    options.axisTitlesPosition = 'in';
    options.fontSize = 11;

    /** Set Chart Colors **/
    options.colors = [  '#0F59A9', // Blue
                        '#E07804', // Orange
                        '#609D09', // Green
                        '#D12112', // Red
                        '#813AA7', // Purple
                        '#808284' // Gray
                     ];

    /** Change cursor when hover on **/
    options.forceIFrame = false;

    /** Legend Options **/
    options.legend = [ { position : 'none' } ];

    /** Bar options **/
    options.bar = [ { groupWidth : '60%' } ];

    /** Chart Area Options **/
    options.chartArea = [ {
                            left : 350,
                            top : 0,
                            width : '100%',
                            height : '95%'
                        } ];

    /** Vertical Axis Options **/
    options.vAxis = [ {
                        title : 'Description of Test Case ',
                        titleTextStyle : {
                            fontSize : 9
                        }
                    } ];

    /** Horizontal Axis Options **/
    options.hAxis = [ {
                        title : 'Time Process(Milliseconds) & Build#',
                        titleTextStyle : {
                            fontSize : 9
                        },
                        gridlines : [ {
                            color: '#F4F4F4',
                            count : 10
                        } ]
                    } ];

    /** Tooltip Options **/
    options.tooltip = [ {
                            textStyle : {
                                fontSize: 13
                            }
                        } ];

    console.log("Table Chart Options : " + JSON.stringify(options));
    return options;
};



/**
 * Defines Table Chart Columns and adds them to the DataTable
 *
 */
reportingTableBarChart.getTableChartColumns = function () {

    /** Get Number of columns **/
    var numElements = reportingTableBarChart.databaseDataResults[0].length;
    var numOfCommonFields = 2;
    var numOfFieldsInSet = 5;

    console.log("Number of Columns : " + numElements);

    /** Testcase Description Value **/
    reportingTableBarChart.gvDataTable.addColumn( {
                                                    type : 'string',
                                                    label : 'Description',
                                                    id : 'Description',
                                                    role : 'domain'
                                                } );


    //reportingTableBarChart.tableChartHeaders.push('Description');

    /** Loop through sets of testcase data to create the correct number of columns **/
    /** Formula: (Number of Database fields returned - 2 (common fields - Description and Diff)) / 5 (number of fields in set) **/
    for ( i = 0; i < ( (numElements - numOfCommonFields) / numOfFieldsInSet); i++) {

        /** Testcase Process Time value **/
        reportingTableBarChart.gvDataTable.addColumn( {
                                                        type : 'number',
                                                        label : 'Processing Time',
                                                        id : 'ProcessingTime',
                                                        role : 'data'
                                                    } );
        //reportingTableBarChart.tableChartHeaders.push('Processing Time');

        /** "Build Number: xxxx" **/
        reportingTableBarChart.gvDataTable.addColumn( {
                                                        type : 'string',
                                                        label : 'Build Number',
                                                        id : 'BuildNumber',
                                                        role : 'annotation'
                                                    } );

        /** "Process Time: xx.xx  Request: xxxxxxx" **/
        reportingTableBarChart.gvDataTable.addColumn( {
                                                        type : 'string',
                                                        label : 'Request',
                                                        id : 'Request',
                                                        role : 'annotationText'
                                                    } );

        /** Testcase Process Time value **/
        reportingTableBarChart.gvDataTable.addColumn( {
                                                        type : 'number',
                                                        label : 'Processing Time Tooltip',
                                                        id : 'ProcessingTimeTooltip',
                                                        role : 'tooltip'
                                                    } );

        /** Category **/
        reportingTableBarChart.gvDataTable.addColumn( {
                                                        type : 'string',
                                                        label : 'Category',
                                                        id : 'Category',
                                                        role : 'interval'
                                                    } );
    }

    /** Diff Value **** HIDE SOMEHOW in tableview **** **/
    reportingTableBarChart.gvDataTable.addColumn( {
                                                    type : 'number',
                                                    label : 'Diff',
                                                    id : 'Diff',
                                                    role : 'data'
                                                } );
    //reportingTableBarChart.tableChartHeaders.push('diff');
}



/**
 * Performance Filter
 *
 * @returns ControlWrapper Object
 *          ControlWrapper Object for Performance Filter
 */
reportingTableBarChart.getFilterPerformance = function () {

    /** Performance Filter object **/
    reportingTableBarChart.gvFilterPerformance = new google.visualization.ControlWrapper();

    reportingTableBarChart.gvFilterPerformance.setControlType('NumberRangeFilter');
    reportingTableBarChart.gvFilterPerformance.setContainerId('chartFilterPerformance');
    reportingTableBarChart.gvFilterPerformance.setOptions( {
                                                                filterColumnLabel : 'Diff',
                                                                minValue : -1000,
                                                                maxValue : 100,
                                                                ui : {
                                                                    label : 'Filter by variation',
                                                                    labelSeparator : '(%)',
                                                                    labelStacking : 'verical'
                                                                }
                                                            } );

    console.log("Table Chart Performance Filter Options : " + reportingTableBarChart.gvFilterPerformance.toJSON());
}



/**
 * Category Filter
 *
 * @returns ControlWrapper Object
 *          ControlWrapper Object for Catagory Filter
 */
reportingTableBarChart.getFilterCategory = function () {

    /** Chart Table Category Filter object **/
    reportingTableBarChart.gvFilterCatagory = new google.visualization.ControlWrapper();

    reportingTableBarChart.gvFilterCatagory.setControlType('StringFilter');
    reportingTableBarChart.gvFilterCatagory.setContainerId('chartFilterCategory');
    reportingTableBarChart.gvFilterCatagory.setOptions( {
                                                            filterColumnIndex : '5', // filter by Category
                                                            matchType : 'exact',
                                                            ui : {
                                                                label : 'Filter by Category'
                                                            }
                                                        } );

    console.log("Table Chart Category Filter Options : " + reportingTableBarChart.gvFilterCatagory.toJSON());
}



/**
 * Description Filter
 *
 * @returns ControlWrapper Object
 *          ControlWrapper Object for Description Filter
 */
reportingTableBarChart.getFilterDescription = function () {

    /** Chart Table Description Filter object **/
    reportingTableBarChart.gvFilterDescription = new google.visualization.ControlWrapper();

    reportingTableBarChart.gvFilterDescription.setControlType('StringFilter');
    reportingTableBarChart.gvFilterDescription.setContainerId('chartFilterDescription');
    reportingTableBarChart.gvFilterDescription.setOptions( {
                                                                filterColumnIndex : '0', // filter by request description
                                                                ui : {
                                                                    label : 'Filter by Description'
                                                                }
                                                            } );

    console.log("Table Chart Description Filter Options : " + reportingTableBarChart.gvFilterDescription.toJSON());
}



/**
 * URL Filter
 *
 * @returns ControlWrapper Object
 *          ControlWrapper Object for URL Filter
 */
reportingTableBarChart.getFilterUrl = function () {

    /** Chart Table URL Filter object **/
    reportingTableBarChart.gvFilterUrl = new google.visualization.ControlWrapper();

    reportingTableBarChart.gvFilterUrl.setControlType('StringFilter');
    reportingTableBarChart.gvFilterUrl.setContainerId('chartFilterUrl');
    reportingTableBarChart.gvFilterUrl.setOptions( {
                                                        filterColumnIndex : '3', // filter by request URL
                                                        matchType : 'any',
                                                        ui : {
                                                            label : 'Filter by URL string'
                                                        }
                                                    } );

    console.log("Table Chart URL Filter Options : " + reportingTableBarChart.gvFilterUrl.toJSON());
}



/**
 * JSON formatted Google Table Chart Bar Chart
 * ????????????????????
 */
reportingTableBarChart.getTableChartView = function () {

    var view = new google.visualization.DataView(reportingTableBarChart.databaseDataResults);
    view.setColumns(reportingTableBarChart.getTableChartColumns());

    console.log("Chart View : " + view.toJSON());

    return view.toJSON();
}



/**
 * Adds simple "element has been loaded" listeners that write to JS console
 *
 */
reportingTableBarChart.addListenerLoaded = function () {

    google.visualization.events.addListener(
        reportingTableBarChart.gvFilterPerformance, 'ready', function() {
                console.log('Performance Filter loaded');
            } );

/*      google.visualization.events.addListener(
        reportingTableBarChart.gvFilterCatagory, 'ready', function() {
                console.log('Category Filter loaded');
            } );

    google.visualization.events.addListener(
        reportingTableBarChart.gvFilterDescription, 'ready', function() {
                console.log('Description Filter loaded');
            }   );

    google.visualization.events.addListener(
        reportingTableBarChart.gvFilterUrl, 'ready', function() {
                console.log('URL Filter loaded');
        } );*/

    google.visualization.events.addListener(
            reportingTableBarChart.gvChartWrapper, 'ready', function() {
                console.log('Bar Chart loaded');
            } );
}



/**
 * Adds a listener to auto resize the Table Chart Dashboard when browser is resized
 *
 */
reportingTableBarChart.addListenerTableChartHeightAutoResize = function () {

    google.visualization.events.addListener(reportingTableBarChart.gvDashboard, 'ready', function() {

        console.log('Resizing Chart...');

        var recordRowsTotal = reportingTableBarChart.gvDataTable.getNumberOfRows();
        var numRows = reportingTableBarChart.gvChartWrapper.getDataTable().getNumberOfRows();
        var expectedHeight = numRows * 60;

        if( numRows == 0 )
            expectedHeight = 60;

        if( parseInt( reportingTableBarChart.gvChartWrapper.getOption('height'), 10 ) != expectedHeight ) {

            $("#recordRowsDispalyed").text(numRows);
            $("#recordRowsTotal").text(recordRowsTotal);

            reportingTableBarChart.gvChartWrapper.setOption('height', expectedHeight);
            reportingTableBarChart.gvChartWrapper.draw();
        }

    } );
}



/**
 * Adds a listener allowing user to click on Table Chart row to view test details
 *
 */
reportingTableBarChart.addListenerTableChartClickRow = function () {

    /** Enable clicking on chart to view testcase detail **/
    google.visualization.events.addListener(reportingTableBarChart.gvChartWrapper, 'select', function (){

        var chartObject = reportingTableBarChart.gvChartWrapper.getChart();
        var selectedItem = chartObject.getSelection()[0];
        var selectedData = reportingTableBarChart.gvChartWrapper.getDataTable();

        if( selectedItem ) {

            var description = selectedData.getValue(selectedItem.row, 0);

            /** Redirect when clicked **/
            window.location.href = '<%=request.getContextPath()%>/report?name=custom&description=' + escape(description); //WTF
        }
    });
}



/**
 * Sets Performance filter result range and updates Performance filter
 *
 */
reportingTableBarChart.setFilterPerformanceRange = function (low, high) {

    reportingTableBarChart.gvFilterPerformance.setState( {
                                                            lowValue : low,
                                                            highValue : high
                                                        } );
    reportingTableBarChart.gvFilterPerformance.draw();
};


/**
 * Sets Performance filter based on URL query modifier 'filter'
 * Is injected when clicking pie chart to view report
 *
 */
reportingTableBarChart.setFilterPerformanceFromUrl = function () {

    var params = new URLSearchParams(location.search);
    var param = params.get('filter');

    if (param != null ) {
        switch(param.toLowerCase()) {
            case 'faster':

                reportingTableBarChart.setFilterPerformanceRange(-100, 0);
                $("#btnAllFaster").attr("disabled", "disabled");
                break;

            case 'slower':

                reportingTableBarChart.setFilterPerformanceRange(0, 100);
                $("#btnAllSlower").attr("disabled", "disabled");
                break;

            case 'unchanged':

                reportingTableBarChart.setFilterPerformanceRange(0, 0);
                $("#unchanged").attr("disabled", "disabled");
                break;

            case 'new':
            default:

                reportingTableBarChart.setFilterPerformanceRange(-1000, -1000);
            break;
        }
    }
};



/**
 * Resets Performance and Category filters
 *
 */
reportingTableBarChart.resetAllFilters = function () {

    /** Reset Performance filter **/
    reportingTableBarChart.setFilterPerformanceRange(-1000, 100);

    /** Reset Category filter **/
    reportingTableBarChart.gvFilterCatagory.setState( { value: '' } );
    reportingTableBarChart.gvFilterCatagory.draw();
};



/**
 * Resets Performance filter, then sets Category filter
 *
 */
reportingTableBarChart.setFilterCategory = function (category) {

    /** Reset Performance filter **/
    reportingTableBarChart.setFilterPerformanceRange(-1000, 100);

    /** Set Category filter **/
    reportingTableBarChart.gvFilterCatagory.setState( { value: category } );
    reportingTableBarChart.gvFilterCatagory.draw();
};



/**
 * Set Database results
 *
 */
reportingTableBarChart.setDatabaseDataResults = function (jsonRecords) {

    reportingTableBarChart.databaseDataResults = jsonRecords;
}



/**
 * Grabs JSON results from database data servlet via Ajax and creates a
 * Google Table Chart
 */
reportingTableBarChart.getReportData = function (urlQuery) {

    databasedata.setRequestQuery(urlQuery);

    /** Check that the server query is set **/
    if (databasedata.requestQuery == null) {

        console.log('databasedata.requestQuery is not set - See databasedata.setRequestQuery()');
        return;
    }

    /** Sends request to database data servlet to grab JSON and turns it into an HTML table **/
    databasedata.getJsonData().done(reportingTableBarChart.setDatabaseDataResults);
};

0 个答案:

没有答案