我想在一页上显示多个 Google 图表。我搜索了一种解决方案,并在此站点上找到了一个。轻松创建新图表的功能。现在它只适用于一张图表,当我添加第二张图表时,它们都不再工作了。 Json 和 div id 是正确的,当我只使用其中 1 个图表的代码时,两者都有效。知道这里的问题/解决方案是什么吗?
$(function() {
var jsonDataClicks = $.ajax({
url: 'ajax/get-total-clicks.php',
dataType: 'json',
async: false
}).responseText;
var jsonDataActiveProducts = $.ajax({
url: 'ajax/get-total-active-products.php',
dataType: 'json',
async: false
}).responseText;
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(function() {
drawChart(jsonDataClicks, 'total_clicks');
});
google.charts.setOnLoadCallback(function() {
drawChart(jsonDataActiveProducts, 'total_active_products');
});
function drawChart(dataInput, containerID) {
var data = new google.visualization.DataTable(dataInput);
var containerDiv = document.getElementById(containerID);
var options = {
vAxis: {
gridlines: {
color: '#ebebeb'
}
},
animation: {
startup: true,
duration: 1000,
easing: 'out'
},
hAxis: {
slantedText: true,
slantedTextAngle: 45,
textStyle : {
fontName: 'Lato',
fontSize: 11,
color: '#6f6f6f'
}
},
vAxis: {
textStyle: {
fontName: 'Lato',
fontSize: 11,
color: '#6f6f6f'
}
},
tooltip: {
textStyle: {
fontName: 'Lato',
fontSize: 11,
color: '#6f6f6f'
}
},
width: 1160,
height: 400,
chartArea: {'width': '80%', 'height': '80%'},
colors: ['#47ab8b'],
legend: 'none'
};
var chart = new google.visualization.ColumnChart(containerDiv);
chart.draw(data, options);
}
});
最佳答案
方法 --> google.charts.setOnLoadCallback
-- 每个页面加载实际上应该只调用一次
相反,请将'callback'
添加到google.charts.load
语句
另外,强烈建议不要使用 async: false
进行 $.ajax
调用
您可以在$.ajax({}).done
上绘制图表
推荐与以下类似的设置...
$(function() {
google.charts.load('current', {
'callback': function () {
drawChart('ajax/get-total-clicks.php', 'total_clicks');
drawChart('ajax/get-total-active-products.php', 'total_active_products');
function drawChart(dataURL, containerID) {
$.ajax({
url: dataURL,
dataType: 'json'
}).done(function (dataInput) {
var data = new google.visualization.DataTable(dataInput);
var containerDiv = document.getElementById(containerID);
var options = {
vAxis: {
gridlines: {
color: '#ebebeb'
}
},
animation: {
startup: true,
duration: 1000,
easing: 'out'
},
hAxis: {
slantedText: true,
slantedTextAngle: 45,
textStyle : {
fontName: 'Lato',
fontSize: 11,
color: '#6f6f6f'
}
},
vAxis: {
textStyle: {
fontName: 'Lato',
fontSize: 11,
color: '#6f6f6f'
}
},
tooltip: {
textStyle: {
fontName: 'Lato',
fontSize: 11,
color: '#6f6f6f'
}
},
width: 1160,
height: 400,
chartArea: {'width': '80%', 'height': '80%'},
colors: ['#47ab8b'],
legend: 'none'
};
var chart = new google.visualization.ColumnChart(containerDiv);
chart.draw(data, options);
});
}
},
'packages':['corechart']
});
});
关于javascript - 多个 Google 图表,只有一个可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40682827/