大家好我正在使用谷歌图表开发一个Web应用程序。我想在每次用户选择时重绘图表这里是我的代码
//Loading google api
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawAllCharts);
function drawAllCharts() {
//Sending server a request
$.post("index.php", {
type: "result"
}, function (data, status) {
handleResponse(data, true)
});
}
//This function handles response of server which is a JSON string
function handleResponse(jsonString, init) {
//Parsing JSON string into object
var obj = JSON.parse(jsonString);
var arrayData = objToStrin(obj); //Converting obj to array
console.log(arrayData);
drawDistChart(arrayData, init);
}
//This function draws first chart
function drawDistChart(arrayData, init) {
//Preparing data
var dataDistribution = new google.visualization.DataTable();
dataDistribution.addColumn('string', "Fitness");
dataDistribution.addColumn('number', "Physical");
dataDistribution.addColumn('number', "Emotional");
dataDistribution.addRows(arrayData);
//Setting few properties
var options = {
title: 'No of People',
backgroundColor: {
fill: 'transparent'
},
hAxis: {
title: 'Wellness Score',
slantedText: true,
titleTextStyle: {
color: 'red'
}
}
};
//Drawing the chart
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(dataDistribution, options);
}
但没有任何反应,请帮助
您需要添加“select”事件侦听器来处理用户选择图表元素:
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length) {
// the user clicked on a chart element
// get row/column information from selection[n].row/column
// do something with the selection
// redraw the chart
chart.draw(dataDistribution, options);
}
});
无需每次都声明new google.visualization.ColumnChart
。
只是chart.draw(dataDistribution, options);
将工作正常。
在chart.draw(dataDistribution, options);
添加function handleResponse