我正在尝试实施Candlestick Google Chart,但我希望能够使用AJAX使用不同的数据重新加载图表。我从Google提供的示例中复制了一些代码,但我遗漏了一些东西 - 我认为这与格式不正确的JSON有关。这是我的调用代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "http://www.mydomain.com/chart_data.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<div style="width: 900px;">
<div style="float: right;">>></div>
<div style="float: left;"><<</div>
</div>
</body>
</html>
chart_data.php如下所示:
{
"rows": [
{c:[{v: 'Mon'}, {v: 12634}, {v: 12818.9}, {v: 12695.3}, {v: 12818.9}]},
{c:[{v: 'Tue'}, {v: 12583.7}, {v: 12694.8}, {v: 12632}, {v: 12795.7}]},
{c:[{v: 'Wed'}, {v: 12559.6}, {v: 12617.4}, {v: 12598.5}, {v: 12764.7}]},
{c:[{v: 'Thu'}, {v: 12415.8}, {v: 12598.5}, {v: 12442.5}, {v: 12670.2}]},
{c:[{v: 'Fri'}, {v: 12309.6}, {v: 12442.9}, {v: 12369.4}, {v: 12539.5}]}
]
}
我猜测JSON数据格式错误也许?但我没有看到任何关于如何填充烛台图表的样本。
对此的任何帮助都将非常感激。谢谢!
答案 0 :(得分:1)
希望这会对你有所帮助,
// first change google.visualization.DataTable to google.visualization.arrayToDataTable and JSON format not perfect.
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
var jsonData = $.ajax({
url: "chart_data.php",
contentType:"application/json",
dataType:"json",
async: false
}).responseText;
var array=$.parseJSON( jsonData);
var data =google.visualization.arrayToDataTable(array,true);
var options = {width: 400, height: 240};
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
</script>
chart_data.php json看起来像这样:
[["Mon",12634, 12818.9, 12695.3, 12818.9], ["Tue", 12583.7, 12694.8, 12632, 12795.7],["Wed", 12559.6, 12617.4, 12598.5, 12764.7],["Thu", 12415.8, 12598.5, 12442.5, 12670.2],["Fri", 12309.6, 12442.9,12369.4, 12539.5]]