无法让谷歌图表/ json数据正常工作

时间:2012-09-28 10:43:51

标签: php json google-visualization

您好我正在尝试使用google的api生成一个带有几个仪表的简单页面。我一遍又一遍地在网上找到的所有信息都无法解决为什么它显示空白页面。我怀疑我的json,因为我以前没用过它。

getData.php输出的json是:

[{"hostname":"bongo","value":24},{"hostname":"chappie","value":78}]

应该生成仪表的php脚本是:

  <html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="jquery-1.6.4.js"></script>
    <script type="text/javascript">

    google.load('visualization', '1', {packages:['gauge']});

    google.setOnLoadCallback(drawChart);


    function drawChart() {
      var jsonData = $.ajax({
          url: "getData.php",
          dataType:"json",
          async: false
          }).responseText;

      var data = new google.visualization.DataTable(jsonData);

    var options = {
          width: 400, height: 120,
          redFrom: 90, redTo: 100,
          yellowFrom:75, yellowTo: 90,
          minorTicks: 5
        };

      var chart = new google.visualization.Guage(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

    </script>
  </head>
  <body>
    <div id='chart_div'></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您的json数据格式不正确,并且误输入Gauge作为Guage。 我纠正了你的代码,它在我的php服务器上运行如下(顺便说一句,你可以嵌套数组并使用json_encode php函数输出符合google Datatable json字符串格式的json字符串):

<head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">

    google.load('visualization', '1', {packages:['gauge']});

    google.setOnLoadCallback(drawChart);


    function drawChart() {
    var jsonData = {
                    cols: [{id: 'Host Name', label: 'Host Name', type: 'string'},
                           {id: 'Value', label: 'Value', type: 'number'}],
                    rows: [{c:[{v: 'bongo'}, {v: 24}]},
                           {c:[{v: 'chappie'}, {v: 78}]}]
                    }

    var data = new google.visualization.DataTable(jsonData);

    var options = {
        width: 400, height: 120,
        redFrom: 90, redTo: 100,
        yellowFrom:75, yellowTo: 90,
        minorTicks: 5
    };

    var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
        chart.draw(data, options);
    }

</script>
</head>
<body>
    <div id='chart_div'></div>
</body>

要进行调试,您可以:     google.visualization.events.addListener(bar_chart_example,'error',function(err){         document.getElementById('bar_chart_example_div')。innerHTML = err.message;     });