django-templates - 谷歌可视化-条形图上的点击事件是Stacked : true

标签 django-templates google-visualization

我正在尝试显示条形图的总值(value),其中 <span> 上的“isStacked: true”当我单击一个栏时位于图表顶部。

我探索 google.visualization.events.addListener 功能的引用开始 here.

当我单击 a 栏时,我收到此错误:

Uncaught TypeError: Cannot read property 'row' of undefined

或者当我更改 row 时至column

Uncaught TypeError: Cannot read property 'column' of undefined

非常感谢任何指点。

这是我的 django 模板:

<script type="text/javascript">   
  $(document).ready(function(){ 
  {% for staff_name, staff_id in params.items %}  
$.ajax({
      url: "{% url user_kpi %}",
      data: { user_stat: {{staff_name}} },
      success: function(responseData) { 
        if (typeof responseData=="object") {                      
          var data = new google.visualization.arrayToDataTable([
            ['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
            ['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
            ['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'], 
            ['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
            ['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ], 
            ['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
            ['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
            ['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
            ['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']]);
          google.setOnLoadCallback(drawVisualization(data, {{staff_name}}));
        }
      }
});
  {% endfor %} 

  });  
  var wrapper;
  function drawVisualization(xdata, id) { 
    // Create and draw the visualization.   
    var visual = 'visualization-'+id.toString();
    //chart = new google.visualization.BarChart(document.getElementById(visual));
    wrapper = new google.visualization.ChartWrapper({
        chartType: 'BarChart',
        dataTable: xdata,
        options: {
                  width:600, height:140,
                  vAxis: {title: null, maxValue: 3500},
                  hAxis: {title: null},

                  animation: {easing: 'in'},
                  axisTitlesPosition: "out",
                  chartArea:{left:0,top:0, right:0, width:"100%",height:"100%"},
                  focusTarget: "category",
                  fontSize: 12,
                  fontName: "Tahoma",
                  legend: {position: 'none'},
                  series: [{color: 'black', visibleInLegend: false}, {}, {},
                           {color: 'red', visibleInLegend: false}],
                  isStacked: true,
                  backgroundColor: '#eee',
                 },
        containerId: visual
    });
    google.visualization.events.addListener(wrapper, 'ready', function() {
      // grab a few details before redirecting
      google.visualization.events.addListener(wrapper.getChart(), 'select', function() {
        chartObject = wrapper.getChart();
        // checking value upon mousehover
        alert(xdata.getValue(chartObject.getSelection()[0].row, 0));
        //alert(xdata.getValue(chartObject.getSelection()[0].column, 0));
      });
    });

    wrapper.draw();
}   

更新:正如asgallant所解释的。

<script type="text/javascript">   
function init () {
{% for staff_name, staff_id in params.items %}
$.ajax({
    url: "{% url user_kpi %}",
    data: { user_stat: {{staff_name}} },
    success: function(responseData) { 
        if (typeof responseData=="object") {                      
            var data = new google.visualization.arrayToDataTable([
                ['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
                ['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
                ['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'], 
                ['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
                ['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ], 
                ['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
                ['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
                ['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
                ['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']
            ]);
            drawVisualization(data, {{staff_name}});
        }
    }
});
{% endfor %}
}
google.load('visualization', '1', {packages:['corechart'], callback: init});

function drawVisualization(xdata, id) { 
  // Create and draw the visualization.   
  var visual = 'visualization-'+id.toString(),
  //chart = new google.visualization.BarChart(document.getElementById(visual));
  wrapper = new google.visualization.ChartWrapper({
      chartType: 'BarChart',
      dataTable: xdata,
      options: {
                width:600, height:140,
                vAxis: {title: null, maxValue: 3500},
                hAxis: {title: null},

                animation: {easing: 'in'},
                axisTitlesPosition: "out",
                chartArea:{left:0,top:0, right:0, width:"100%",height:"100%"},
                focusTarget: "category",
                fontSize: 12,
                fontName: "Tahoma",
                legend: {position: 'none'},
                //orientation: "vertical"
                series: [{color: 'black', visibleInLegend: false}, {}, {},
                         {color: 'red', visibleInLegend: false}],
                isStacked: true,
                backgroundColor: '#eee',
               },
      containerId: visual
  });
  google.visualization.events.addListener(wrapper, 'ready', function() {
    var chart = wrapper.getChart();
    google.visualization.events.addListener(chart, 'select', function() {
        var selection = chart.getSelection();
        if (selection.length) {
            // the user selected a bar
            alert(xdata.getValue(selection[0].row, 0));
            //alert(selection.length);
        }
        else {
            alert('no selection');// the user deselected a bar
        }
    });
  });

  wrapper.draw();
}   

错误: Uncaught Error :未定义无效的行索引。应在 [0-7] 范围内。

由 asgallant 修正 转动这条线alert(xdata.getValue(selection.row, 0));进入alert(xdata.getValue(selection[0].row, 0));

最佳答案

首先,您的 AJAX 调用应该在来自 google 加载器的回调中进行,而不是来自文档就绪处理程序(这保证了当您尝试使用 API 组件时可视化 API 可用):

function init () {
    {% for staff_name, staff_id in params.items %}
    $.ajax({
        url: "{% url user_kpi %}",
        data: { user_stat: {{staff_name}} },
        success: function(responseData) { 
            if (typeof responseData=="object") {                      
                var data = new google.visualization.arrayToDataTable([
                    ['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
                    ['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
                    ['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'], 
                    ['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
                    ['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ], 
                    ['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
                    ['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
                    ['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
                    ['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']
                ]);
                drawVisualization(data, {{staff_name}});
            }
        }
    });
    {% endfor %}
}
google.load('visualization', '1', {packages:['corechart'], callback: init});

然后,在您的 drawVisualization 中函数,你有几个问题:首先,wrapper是一个全局对象,因此每次调用 drawVisualization 时它都会被覆盖;这是问题的主要原因,因为一个图表会触发“选择”事件,但是 wrapper指的是最后绘制的图表,而不是单击的图表(因此, wrapper.getChart().getSelection() 调用返回一个空数组,空数组的元素 0 是 undefined ,并且 undefined 没有行或列属性) 。您需要将包装器设置为 drawVisualization 的本地包装器函数而不是全局。删除这一行:

var wrapper;

并添加 var到该行的开头:

wrapper = new google.visualization.ChartWrapper({

然后您需要调整事件处理程序来测试选择数组的长度,因为用户可以单击一个栏两次,这会选择然后取消选择该栏,从而产生一个空数组,并且您会得到相同的结果错误。事件处理程序需要如下所示:

google.visualization.events.addListener(wrapper, 'ready', function() {
    var chart = wrapper.getChart();
    google.visualization.events.addListener(chart, 'select', function() {
        var selection = chart.getSelection();
        if (selection.length) {
            // the user selected a bar
            alert(xdata.getValue(selection[0].row, 0));
        }
        else {
            // the user deselected a bar
        }
    });
});

关于django-templates - 谷歌可视化-条形图上的点击事件是Stacked : true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963158/

相关文章:

django - 如何在 django 项目中添加 css 和 jquery 文件?

javascript - Google 图表柱形图宽度

使用 Google 可视化 API 到 Google 表格的 Javascript Query.setQuery() 给出 'Missing query for request id: undefined"

javascript - Google 图表 - 能否将柱形图中的柱与图表的中心对齐?

django - 如何在 django 模板中嵌入 SVG 图像

python - Django模板中字典的循环问题

python - 如何使用 Django 的 'with' 模板标签保存比较结果?

python - AbstractBaseUser 电子邮件作为用户名验证

google-maps - 谷歌分析就像区域 map

javascript - 如何使用 vue-google-charts 创建组织结构图