【问题标题】:Filling Google Charts API, getting "Column header row must be an array."填充 Google Charts API,得到“列标题行必须是一个数组”。
【发布时间】:2020-05-18 14:01:45
【问题描述】:

我想用我的函数中的数据填充 Google 图表。我还定义了标题行,但我得到的是"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 解决方案(错误消失了)。所以我现在看到“错误:未定义容器”。 这不应该发生。我使用以下结构:

<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.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);
}

以及关于 gCSC 部分的巨大成功函数。

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");
      }  
}

编辑

单行输出示例:

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

多行输出示例:

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

【问题讨论】:

    标签: javascript jquery arrays charts google-visualization


    【解决方案1】:

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

    数据集应该类似于...

    [
      ['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);
    
      ...
    

    编辑

    看来 drawChart 函数正在从 google 的 load 语句中调用,
    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的load语句会等待文件加载,
    在调用回调函数之前。
    所以这取代了对 jquery 的 $(document).ready 函数的需求,
    或标准的window.addEventListener('load', ... 函数。

    另一件事,load 语句返回一个承诺,
    可以用来代替setOnLoadCallback

    先尝试加载谷歌图表,然后再进行其他操作。
    当 promise 返回时,调用加载数据并执行成功处理程序的函数。

    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'是给他们的材料条形图...

    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>

    【讨论】:

    • 感谢您的帮助。目前看来还不错。但我仍然面临问题。当我解决我的新问题时,我可以稍后检查你的答案吗?
    • 我可能需要你的帮助。因为对于那些没有 JS 经验的人来说,这有点奇怪。你能看看我更新的帖子吗?
    • 我明白了,你能分享一下绘制图表的其余代码,包括谷歌图表的加载位置吗?
    • 参见上面的EDIT,内容很多,如果我需要更好地表达,请告诉我...
    • 您有多行和一个标题?您能否分享您遇到问题的数据样本? --> console.log(JSON.stringify(data_coll));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多