没有消息或错误ID的谷歌图表错误

时间:2016-05-31 10:49:59

标签: javascript jquery ajax google-visualization

就像我在标题中提到的那样,我在图表中得到一个错误,但没有消息,所以我无法解决它。图表也很好用。这是图表的图片。它看起来很好,图表的onhover和onclick功能也正常工作。

error pic

这是我的图表JS。标签可能有点奇怪,因为我将它插入stackoverflow的方式。它与示例图表几乎相同。我添加了监听器来检查窗口大小是否发生变化,并且我在页面上有几个按钮,它们给json调用一个值来查询。最后有一个函数来获取$ _GET变量。

var clicked = false;
var nr = "";
$(function () {

        $('button[id^="chart_button"]').on('click', function (e) {
        clicked = true;
        nr = $(this).attr('id');
        drawChart();
        });

    //check window size
    if (document.addEventListener){
        window.addEventListener("resize", drawChart);
    }else if (document.attachEvent){
        window.attachEvent("onresize", drawChart);
    }else{
        window.resize = drawChart;
    }
});

function getstart(){
    if(clicked){
        return $('#'+nr).attr('value');
    }
    return $('#tabbuttongroup').children().first().attr('value');
}

google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var jsonData = $.ajax({
        dataType: "json",
        url: "modules/Forecast/models/getForecastChart.php",
        data: {
            id: getQueryVariable('record'),
            start_date: getstart()
        },
        async: false
    }).responseText;

    var mydata = $.parseJSON(jsonData);

    var data = new google.visualization.DataTable();

    data.addColumn("datetime", "Date");
    data.addColumn("number", "Actual Amount");
    data.addColumn("number", "Forecast Amount");
    data.addColumn("number", "Actual Price");
    data.addColumn("number", "Forecast Price");

    for(var i = 0; i < mydata['forecast'].length; i++){
        var datesplit = String(mydata['forecast'][i][2]).split('-');
        var date = new Date(datesplit[0], datesplit[1]-1, datesplit[2]);

        data.addRow([
            date,
            Number(mydata['actual'][i][5]),
            Number(mydata['forecast'][i][5]),
            Number(mydata['actual'][i][6]),
            Number(mydata['forecast'][i][6])
        ]);
    }

    var options = {
        bars: 'vertical',
        hAxis: {
            title: "Date",
            gridlines: {
                count: -1,
                units: {
                    days: {
                        format: ["dd MMM"]
                    }
                }
            }
        },
        vAxis: {
            format: 'decimal'
        },
        colors: ['#00AAFF', '#0088FF', '#EEDD55', '#EEBB55']
    };

    var chart = new google.charts.Bar(document.getElementById('chart_div'));
    chart.draw(data, options);
}

function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if (pair[0] == variable) {
                        return pair[1];
                }
        }
        alert('Query Variable ' + variable + ' not found');
}

2 个答案:

答案 0 :(得分:2)

您可以在图表上收听'error'事件,可能提供更多详细信息

google.visualization.events.addListener(chartInstance, 'error', handler);

handler会收到两个属性id&amp; message

然后您可以removeError使用id或使用图表容器removeAll

另外,在使用 Material 图表时,您应该转换选项...
google.charts.Bar.convertOptions(options)

(注意网格线的差异)

参见以下示例......

google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var mydata = {forecast: [
      [new Date(2016,04,31), 5, 6, 7, 8],
      [new Date(2016,05,01), 4, 8, 9, 8],
      [new Date(2016,05,02), 8, 4, 0, 6],
      [new Date(2016,05,03), 2, 2, 1, 3]
    ]};

    var data = new google.visualization.DataTable();

    data.addColumn("datetime", "Date");
    data.addColumn("number", "Actual Amount");
    data.addColumn("number", "Forecast Amount");
    data.addColumn("number", "Actual Price");
    data.addColumn("number", "Forecast Price");

    for(var i = 0; i < mydata['forecast'].length; i++){
        data.addRow([
            mydata['forecast'][i][0],
            mydata['forecast'][i][1],
            mydata['forecast'][i][2],
            mydata['forecast'][i][3],
            mydata['forecast'][i][4]
        ]);
    }

    var options = {
        bars: 'vertical',
        hAxis: {
            title: "Date",
            gridlines: {
                count: -1,
                units: {
                    days: {
                        format: ["dd MMM"]
                    }
                }
            }
        },
        vAxis: {
            format: 'decimal'
        },
        colors: ['#00AAFF', '#0088FF', '#EEDD55', '#EEBB55']
    };

    var container = document.getElementById('chart_div');
    var chart = new google.charts.Bar(container);

    // throw error for testing
    google.visualization.events.addListener(chart, 'ready', function () {
      throw new Error('Test Google Error');
    });

    // listen for error
    google.visualization.events.addListener(chart, 'error', function (err) {
      // check error
      console.log(err.id, err.message);

      // remove error
      google.visualization.errors.removeError(err.id);

      // remove all errors
      google.visualization.errors.removeAll(container);
    });

    // convert options
    chart.draw(data, google.charts.Bar.convertOptions(options));
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

答案 1 :(得分:0)

为什么不 KISS 用 css 隐藏元素,就像这样:

[id^="google-visualization-errors"] {
    display: none;
}```