簡體   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