繁体   English   中英

仅在有数据时显示Google图表

[英]Displaying a Google Chart only when data is present

我有一个使用SQL数据的Google折线图。 但是,当查询返回0行时,它将在页面上显示一个大的空图表。 我想显示一些文字,说没有数据。 我尝试将图表函数包装在另一个函数中,如果存在数据,该函数将调用该函数,但是即使存在数据,也不会显示任何内容。 这是我的一些代码:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function displayChart()
{
    $(document).ready(function()
    {
        google.setOnLoadCallback(drawChart);
    });
}
function drawChart() 
{
// Here we tell it to make an ajax call to pull the data from the .json file
    var jsonData = $.ajax({
    url: "Data.json",
    dataType:"json",
    async: false
}).responseText;

// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);

// Options for the graph, we set chartArea to get rid of extra whitespace
var options = {
                'width':1300,
                'height':500,
                'chartArea': {top:'10%', left:'5%', height:'75%', width:'85%'}
              };

// Instantiate and draw our chart, passing in some options and putting it in the chart_div.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options); 
}
</script>
<?

...

if($got_data == true)
{
    displayChart();
}
else
    echo "There is no data";

对我做错了什么有什么想法,或者有更好的方法可以做到这一点? 提前致谢!

正如Serg的评论所说,您需要设置是否在ajax调用的回调中显示图表。 这是因为当您调用$.ajax()时,从ajax调用返回的数据不存在也不可访问。 如果您在JQuery AJAX页面上往下看,将会看到几个如何处理来自ajax调用的数据的示例,但是您所寻找的将类似于以下内容:

$.ajax({
    url: "Data.json",
    dataType:"json",
    async: false
}).complete(function(data) {
    if (data) {
        // draw chart
    } else {
        // say no data
    }
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM