我想使用我使用javascript从SQL服务器获取的数据来显示谷歌图表。但我得到IE错误“无法获取属性arrayToDataTable”,即使我已经添加谷歌图表JS。我已通过提醒检查数据,数据正常。如何解决这个问题?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var array = loadData();
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawChart(array));
function loadData(){
var array = [
['Year', 'Sales', 'Expenses', 'Profit']
];
//Connection
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Provider=SQLOLEDB.1;Password=Password1234;Persist Security Info=True;User ID=sa;Initial Catalog=all_data;Data Source=172.16.11.90";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM bar_chart", connection);
rs.MoveFirst;
while(!rs.eof)
{
array.push([rs.fields(0), parseInt(rs.fields(1)), parseInt(rs.fields(2)), parseInt(rs.fields(3))]);
rs.movenext;
}
rs.close;
connection.close;
return array;
}
function drawChart(x) {
alert(x[4][3]);
var data = google.visualization.arrayToDataTable(x);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, options);
}
</script>
这是我的HTML:
<body>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>
</body>
答案 0 :(得分:0)
发生此错误,因为google.setOnLoadCallback
函数需要回调作为参数。
替换:
var array = loadData();
google.setOnLoadCallback(drawChart(array));
在这种情况下,
drawChart
函数立即被调用 等待谷歌可视化API加载
使用:
google.setOnLoadCallback(function () {
var array = loadData();
drawChart(array);
});
示例强>
google.load("visualization", "1.1", { packages: ["bar"] });
google.setOnLoadCallback(function () {
var data = generateData();
drawChart(data);
});
function generateData() {
var data = [
['Year', 'Sales', 'Expenses', 'Profit']
];
for (var year = 2000; year < 2010; year++) {
data.push([year.toString(), getRandomArbitrary(100, 200), getRandomArbitrary(100, 400), getRandomArbitrary(100, 500)]);
}
return data;
}
function drawChart(data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(dataTable, options);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>