首页 > 解决方案 > 使用谷歌图表创建表格图表

问题描述

大家好,我只是想用下面这段代码中的代码制作一个谷歌图表表,我正在通过 axios 调用一个公共 api,但我无法将数据插入到表行中,你能告诉我我在做什么错吗. API = https://dummy.restapiexample.com/api/v1/employees

我想从这个 api 的数据创建一个 html 表。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Visualization API Sample</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<!--
  One script tag loads all the required libraries!
-->
<script type="text/javascript"
      src='https://www.gstatic.com/charts/loader.js'></script>
<script>
  
          const age=[];
          const emp_name=[];
          const salary=[];
          const id=[];

            axios.get('https://dummy.restapiexample.com/api/v1/employees')
            .then(response=> {
                console.log("Response",response.data.data);
                for(const obj of response.data.data){
                    console.log(obj);
                    age.push(obj.employee_age);
                    emp_name.push(obj.employee_name);
                    salary.push(obj.employee_salary);
                    id.push(obj.id);
                    
                }
                for(var i=0; i<emp_name.length; i++){
                console.log(
                [id[i],emp_name[i],salary[i],age[i]]
                )
        }
            })
                
            .catch(err=>{
                console.log("errr",err);
            })
            
      google.charts.load('current', {'packages':['table']});
      google.charts.setOnLoadCallback(drawTable);

      function drawTable() {
        var data = new google.visualization.DataTable();
        data.addColumn('number', 'Id');
        data.addColumn('string', 'Employee Name');
        data.addColumn('number', 'Employee Salary');
        data.addColumn('number', 'Employee Age');
        
        for(var i=0; i<id.length; i++){
          data.addRows([
            [id[i],emp_name[i],salary[i],age[i]]
          ])
        }
        

      
        

        var table = new google.visualization.Table(document.getElementById('table_div'));

        table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
      }
</script>
</head>
<body>
  <div id="table_div" style="height: 400px; width: 400px;"></div>
</body>
</html>

标签: javascript

解决方案


推荐阅读