填充 Google 个图表 API,获得 "Column header row must be an array."

Filling Google Charts API, getting "Column header row must be an array."

我想用我的函数中的数据填充 Google 图表。我还定义了 header 行,但我得到的是 "Column header row must be an array."。我该如何解决?我使用了以下代码。

    var data_coll = "";
    var header_x = "['Skill', 'Scoring']";
    data_coll += header_x+',';
    if (skill_info["category"]==="gCSC")
    {
      qcat = 'gCSC';
      for (var x = 0;x<skill_info["data"].length;x+=1)
      {
        ind_name = skill_info["data"][x]["fn"]+" "+skill_info["data"][x]["ln"];
        if ((x<skill_info["data"].length) && (x>0))
        {
          data_coll += ",";
        }
        data_coll += "['"+ind_name+"',"+skill_info["data"][x]["value"]+"]";
      }
      drawChart(data_coll);

我也试过var header_x = ['Skill', 'Scoring'];var header_x = array('Skill', 'Scoring';

drawChart 是我调用的函数,用于绘制图表 data_call 在其中插入 arrayToDataTable() 的数据。

更新: 我有 WhiteHats 解决方案,看起来不错(错误消失了)。所以我现在看到 "Error: Container is not defined"。 这不应该发生。我使用以下结构:

<div class="container h-100">
  <div class="row h-100 justify-content-center align-items-center">
    <form class="col-12">
      <div class="form-group">
        <div class='elm_emprat pl-3' id="pollingstation"> 
          <div class='btn-group' role='group' aria-label='Basic example'>
            <div  aria-label='Basic example'>
              <div class='btn-group btn-group-toggle' data-toggle='buttons' role='group' id="polloptions">

              </div>
            </div>
          </div> 
      </div>
    </form>   
  </div>  
</div>

我设置了以下内容

var chart = new google.visualization.BarChart(document.getElementById('polloptions'));

所以元素被定义了。也许我错过了什么?

更新 2: 函数定义Google图表

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

// Draw the chart and set the chart values
function drawChart(data_coll) {
      var data = google.visualization.arrayToDataTable([
        data_coll
      ]);

      var options = {
        title: 'Company Skill Comparison',
        chartArea: {width: '50%'},
        width: '100%',
        height: '75%',
        colors: ['#343a40'],
        backgroundColor: { fill:'transparent' },
        hAxis: {
          title: 'Scoring',
          minValue: 0,
          viewWindow: {
            max:100,
            min:0
          }
        },
        vAxis: {
          title: 'Skill'
        }
      };

  // Display the chart inside the <div> element with id="piechart"
  var chart = new google.visualization.BarChart(document.getElementById('polloptions'));
  chart.draw(data, options);
}

还有巨大的 successFunction,它是关于 gCSC-part。

function successHandler(data)
{
      console.log(data);
      var skill_info = JSON.parse(data);
      if ((skill_info.status === 1) && (skill_info.category === "cp") && (skill_info.code === 200)) {
        console.log(skill_info)
        console.log("success loading");                
        //var x,y,dsb,data_coll,ind_name,skill_info,qt,qtx,q_set,q_options='';
        for(var x = 0;x<skill_info["data"].length;x+=1)
        {
        var qt = "<div class='pb-3'><h1 class='display-5' data-panel='cp' id='question_text_"+x+"'>"+skill_info["data"][x]["question_text"]+"</h1></div>";
        console.log(skill_info["data"][x]["question_text"]);
        var option_y = '';
          for(var y = 0;y<skill_info["data"][x]["options"].length;y+=1)
          {             
            option_y += "<label class='btn btn-outline-dark'><input type='radio'  name='options_"+skill_info["data"][x]["id"]+"' value='"+skill_info["data"][x]["options"][y]["answer_value"]+"' autocomplete='off'>"+skill_info["data"][x]["options"][y]["answer"]+"</label>";
            console.log(skill_info["data"][x]["options"][y]["answer_value"]);            
          }
          var q_options = '<div class="btn-group btn-group-toggle" data-toggle="buttons" role="group" id="polloptions">'+option_y+'</div>';
          option_y = '';
          if(x==0)
          {
            dsb = " style='display:block' ";
          }
          else
          {
            dsb = " style='display:none' ";
          }
          document.getElementById("pollingstation").innerHTML += "<div class='elm_emprat pl-3 elm_x_"+x+"' id='pollingstation' "+dsb+">"+qt+q_options+"</div>"; 
        }
      }
      else if((skill_info.status === 1) && (skill_info.category !== "cp") && (skill_info.code === 200))
      {
        console.log(skill_info)
        console.log("success loading");                
        var data_coll = [['Skill', 'Scoring']];

        if(skill_info["category"]==="gCSC")
        {
          qcat = 'gCSC';
          skill_info["data"].forEach(function (row) {
            data_coll.push([row["fn"] + " " + row["ln"], row["value"]]);
          });


          console.log(data_coll);
          drawChart(data_coll);
          qtx = "Top "+skill_info["data"][0]["skill"]+" Skillers @ "+skill_info["data"][0]["name"];
          q_set = '<div class="btn-group btn-group-toggle" data-toggle="buttons" role="group" id="polloptions">'+data_coll+'<button class="sbmt_frm">Next</button></div>';          
        }
        else if (skill_info["category"]==="gRU")
        {
          qcat = 'gRU';          
          qtx = "How do you rate "+skill_info["data"][0]["first_name"]+" "+skill_info["data"][0]["last_name"]+"'s "+skill_info["data"][0]["skill"]+" skill?";
          q_options = "<label class='btn btn-outline-dark'><input type='radio' name='options_"+skill_info["data"][0]["id"]+"_"+skill_info["data"][0]["skill_id"]+"' value='1' autocomplete='off'>0-20</label>";
          q_options += "<label class='btn btn-outline-dark'><input type='radio' name='options_"+skill_info["data"][0]["id"]+"_"+skill_info["data"][0]["skill_id"]+"' value='2' autocomplete='off'>21-40</label>";
          q_options += "<label class='btn btn-outline-dark'><input type='radio' name='options_"+skill_info["data"][0]["id"]+"_"+skill_info["data"][0]["skill_id"]+"' value='3' autocomplete='off'>41-60</label>";          
          q_options += "<label class='btn btn-outline-dark'><input type='radio' name='options_"+skill_info["data"][0]["id"]+"_"+skill_info["data"][0]["skill_id"]+"' value='4' autocomplete='off'>61-80</label>";
          q_options += "<label class='btn btn-outline-dark'><input type='radio' name='options_"+skill_info["data"][0]["id"]+"_"+skill_info["data"][0]["skill_id"]+"' value='5' autocomplete='off'>81-100</label>";  
          q_set = '<div class="btn-group btn-group-toggle" data-toggle="buttons" role="group" id="polloptions">'+q_options+'<button class="sbmt_frm">Next</button></div>';
        }
        else if (skill_info["category"]==="gSC")
        {
          qcat = 'gSC';          
          qtx = "Your most recent skill changes";
          q_set = "<button class='sbmt_frm'>Next</button>";
        }    
        else if (skill_info["category"]==="gPM")
        {
          qcat = 'gPM';
          qtx = "Do you know "+skill_info["data"]["first_name"]+" "+skill_info["data"]["last_name"]+" ("+skill_info["data"]["position"]+" @ "+skill_info["data"]["company_name"]+")";
          q_options = "<label class='btn btn-outline-dark'><input type='radio' name='options_"+skill_info["data"]["id"]+"' value='2' autocomplete='off'>Yes</label>";
          q_options += "<label class='btn btn-outline-dark'><input type='radio' name='options_"+skill_info["data"]["id"]+"' value='1' autocomplete='off'>No</label>";          
          q_set = "<div class='btn-group btn-group-toggle' data-toggle='buttons' role='group' id='polloptions'>"+q_options+"<button class='sbmt_frm'>Next</button></div>";
        }               
        var qt = "<div class='pb-3'><h1 class='display-5' id='question_text_0' data-panel='"+qcat+"'>"+qtx+"</h1></div>";
        document.getElementById("pollingstation").innerHTML += "<div class='elm_emprat pl-3 elm_x_"+x+"' id='pollingstation'>"+qt+q_set+"</div>"; 

      }
      else {
         console.log(skill_info);
         console.log("failure loading");
      }  
}

编辑

one-row 输出示例:

[["Skill","Scoring"],["Jim","3.00"]]

样本multi-row-output:

[["Skill","Scoring"],["Jim","3.00"],["Reid","5.16"],["Akshay","6.00"]]

整个数据集必须是一个数组,
并且数据集的每一行必须是一个数组...

数据集应该类似于...

[
  ['Skill', 'Scoring'],
  ['name', 10],
]

如果您使用 javascript,则无需构建字符串,
直接构建数组...

var data_coll = [['Skill', 'Scoring']];
if(skill_info["category"]==="gCSC")
{
  qcat = 'gCSC';
  skill_info["data"].forEach(function (row) {
    data_coll.push([row["fn"] + " " + row["ln"], row["value"]]);
  });
  drawChart(data_coll);

  ...

编辑

似乎正在从 google 的加载语句中调用 drawChart 函数,
successHandler 函数完成构建内容之前,这里...

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

// Draw the chart and set the chart values
function drawChart(data_coll) {
  ...

因为google图表每次加载页面只需要加载一次,
我喜欢先加载它,然后再加载页面上的其他内容。
此外,google 的 load 语句将等待文档加载,
在调用回调函数之前。
所以这取代了 jquery 的 $(document).ready 函数
的需要 或标准 window.addEventListener('load', ... 函数。

另一件事,load声明returns一个承诺,
可以用来代替 setOnLoadCallback

首先尝试加载 google 图表,然后再进行其他操作。
当承诺 returns 时,则调用加载数据并执行成功处理程序的函数。

google.charts.load('current', {
  packages:['corechart']
}).then(function () {  // this is the promise function to replace the callback

  // call function that loads the data here
  $.ajax or whatever...

});

然后你的 drawChart 函数将在成功处理程序中被调用,
创建内容后。


注意:如果您使用的是条形图...

google.visualization.BarChart

那么你不需要加载'bar'包,只需要加载'corechart'包。

'bar' 用于他们的 material 条形图...

google.charts.Bar

编辑 2

因为我们正在构建一个数组数组,
无需在此处包含初始数组...

  var data = google.visualization.arrayToDataTable([
    data_coll
  ]);

更改为...

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

编辑 3

提供的数据在这里似乎工作正常,
从数值中删除引号后...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  drawChart([["Skill","Scoring"],["Jim",3.00],["Reid",5.16],["Akshay",6.00]]);
});

function drawChart(data_coll) {
  var data = google.visualization.arrayToDataTable(data_coll);

  var options = {
    title: 'Company Skill Comparison',
    chartArea: {width: '50%'},
    width: '100%',
    height: '75%',
    colors: ['#343a40'],
    backgroundColor: { fill:'transparent' },
    hAxis: {
      title: 'Scoring',
      minValue: 0,
      viewWindow: {
        max:100,
        min:0
      }
    },
    vAxis: {
      title: 'Skill'
    }
  };

  var chart = new google.visualization.BarChart(document.getElementById('polloptions'));
  chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="polloptions"></div>