我正在尝试使用googlechartapi来显示一些图表。图表的数量和图表类型一样是动态的。目前,我只使用饼图类型,但将添加到它。
页面已加载,图表(代码中的小部件)的数量/类型如下所示:
<script> var widgets = {}; // Load Charts and the corechart package. google.charts.load('current', {'packages':['corechart']}); // Draw the pie chart and bar chart when Charts is loaded. google.charts.setOnLoadCallback(buildWidgets); $.ajax({ type: 'get', url: '/api/getPageWidgets.jsp', data: {method:'' , id: <%=custPage%> // , viewSampleId: <%=custSurveyId%> }, dataType: 'json', async: false, success: function(result){ widgets = result.widgets; } }); $(function(){ buildWidgets(widgets); }); </script>
(小工具.js) 我有一个循环遍历所有小部件并调用 build{charttype}Chart 构建饼图的功能是:
build{charttype}Chart
function buildPieChart(data){ var chartId = "chart-"+data.id // google.charts.setOnLoadCallback(drawChart); var ib = '<div id="'+chartId+'" class=" col-'+data.layout.w+'">'; var rd = getChartData(data.subType,data.dataConfig) // console.log(rd); $("#widget-holder").append(ib); var chart = new google.visualization.PieChart(document.getElementById(chartId)); chart.draw(rd, {width: 400, height: 240}); }
但我显然没有正确加载google内容,因为我遇到了以下错误:
因为图表的数量和类型是未知的,所以什么是加载google可视化的正确方法。这样他们就能工作了。
你的问题之一是时机, ajax调用在googlecharts完成加载之前运行。
建议先加载谷歌图表, 每页只需加载一次, 然后你可以根据需要画尽可能多的图表。
一旦google加载了,就可以调用ajax。 也, async: false 在ajax上,使用 done 而不是回调。
async: false
done
完成ajax后,继续 buildWidgets .
buildWidgets
建议进行以下设置。。。
<script> google.charts.load('current', { packages:['corechart'] }).then(function () { $.ajax({ type: 'get', url: '/api/getPageWidgets.jsp', data: {method:'', id: <%=custPage%>, //viewSampleId: <%=custSurveyId%> }, dataType: 'json' }).done(function (result) { buildWidgets(result.widgets); }); }); </script>