简体   繁体   English

仅在有数据时显示Google图表

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

I have a Google Line Chart that uses SQL data. 我有一个使用SQL数据的Google折线图。 However, when 0 rows are returned by the query, it displays a big empty chart on the page. 但是,当查询返回0行时,它将在页面上显示一个大的空图表。 I would like to instead display some text saying that there is no data. 我想显示一些文字,说没有数据。 I tried wrapping the chart functions inside another function that I call if data is present, but nothing was displayed, even if the data was present. 我尝试将图表函数包装在另一个函数中,如果存在数据,该函数将调用该函数,但是即使存在数据,也不会显示任何内容。 Here is some of my code: 这是我的一些代码:

<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";

Any idea on what I am doing wrong, or a better way to accomplish this? 对我做错了什么有什么想法,或者有更好的方法可以做到这一点? Thanks in advance! 提前致谢!

As Serg's comment says, you need to set whether display your chart in a callback from your ajax call. 正如Serg的评论所说,您需要设置是否在ajax调用的回调中显示图表。 This is because the data that will be returned from your ajax call is not present nor accessible when you call $.ajax() . 这是因为当您调用$.ajax()时,从ajax调用返回的数据不存在也不可访问。 If you look down on the JQuery AJAX page you will see several examples of how to deal with your data from the ajax call, but what you are looking for will be something like the following: 如果您在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