2012-11-26 38 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

相關問題