Google Chart API无效的行索引。应该在[0-4]

时间:2019-01-25 09:14:34

标签: javascript charts google-visualization

我正在为自己的组织开发报告,因为我正在使用Google图表,而我正在使用条形图作为报告。

如果我对google.visualization.DataTable()中的值进行硬编码,这是我用来显示图表的Java脚本代码;条形图正确呈现。如果我尝试从Java脚本对象中获取值,则会显示错误。enter image description here

我正在使用的Java脚本代码是

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
  
  var obj = JSON.parse('<?php echo json_encode($enroled_course) ?>');

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

function drawMaterial() {

  //  alert(obj.toSource());

 var data = new google.visualization.DataTable();
  data.addColumn('string', 'Course Name');
  data.addColumn('number', 'Completion Percentage');
  
 data.addRows(20);

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {   
    var val = obj[key];
    var course_percent=val.id;
    var course_name=val.fullname;
   data.setCell(course_name,course_percent);
    //console.log(val);
  }
}


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

// Declare columns
data.addColumn('string', 'Employee Name');
data.addColumn('datetime', 'Hire Date');

// Add data.
data.addRows([
  ['Mike', {v:new Date(2008,1,28), f:'February 28, 2008'}], // Example of specifying actual and formatted values.
  ['Bob', new Date(2007,5,1)],                              // More typically this would be done using a
  ['Alice', new Date(2006,7,16)],                           // formatter.
  ['Frank', new Date(2007,11,28)],
  ['Floyd', new Date(2005,3,13)],
  ['Fritz', new Date(2011,6,1)]
]);*/

      var materialOptions = {
        chart: {
          title: 'Enrolled courses Details'
        },
        hAxis: {
          title: 'Completion Percentage',
          minValue: 0
        },
        vAxis: {
          title: 'Courses'
        },
        bars: 'vertical'
      };
      var materialChart = new google.charts.Bar(document.getElementById('chart_div'));
      materialChart.draw(data, materialOptions);
    }
</script>
<div id="chart_div"></div>
<div class="container">
  <div class="row rounded">
    <div class="col-sm border">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
  </div>
</div>

如果有人能说为什么我试图在data.setCell()中插入字符串时,我得到无效的行索引错误,我将不胜感激。方法。我看到了类似的错误,但找不到原因。

1 个答案:

答案 0 :(得分:0)

数据表方法setCell采用以下参数...

setCell(rowIndex, columnIndex, value);

您正在尝试传递行值,这会导致错误...

data.setCell(course_name,course_percent);

相反,不要一开始就添加行,(删除-> data.addRows(20);
一旦有了值,就添加它们...

请参阅以下代码段...

var data = new google.visualization.DataTable();
data.addColumn('string', 'Course Name');
data.addColumn('number', 'Completion Percentage');

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {   
    var val = obj[key];
    var course_percent=val.id;
    var course_name=val.fullname;
    data.addRow([course_name,course_percent]);
  }
}