2012-11-26 41 views
0

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

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

任何想法,我在做什么错,或更好的方式来实现呢?提前致谢!

+0

如何以及在何处是价值$ got_data设置了? – dreamerkumar

+1

使用$ .ajax而不是同步调用的回调 – Sergii

+0

@Vishal Kumar $ got_data在sql查询后设置为true,如果返回一个或多个行。我已经检查过,并且这个工作正常 – user1504583

回答

0

正如Serg的评论所说,您需要设置是否在来自ajax调用的回调中显示您的图表。这是因为当您致电$.ajax()时,将从您的ajax呼叫中返回的数据不存在,也无法访问。如果你看不起JQuery AJAX page你会看到如何处理来自AJAX调用数据的几个例子,但你正在寻找的将是类似如下:

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

但是ajax调用在drawChart函数中。我将不得不从drawChart函数内调用drawChart函数?我知道递归函数,但我不确定这会起作用 – user1504583

+0

它应该是类似于'getChartData',它包含ajax调用,那么ajax complete函数会调用'drawChart'函数 – zbrunson

相关问题