我目前正在尝试显示一个谷歌图表,其中填充了我从数据源中提取的信息。我与已建立的数据库有连接,我可以查询我想要的数据并将结果存储在json对象中。我遇到的问题是显示图表。我很近,但还没到。这是我在PHP代码中的内容
`<?php
$mysqli =mysqli_connect('localhost', 'root', '', 'prueba');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = mysqli_query($mysqli, 'SELECT * FROM pizza');
if (!$sql) {
die("Error running $sql: " . mysql_error());
}
$results = array(
'cols' => array(
array('label' => 'Topping', 'type' => 'varchar'),
array('label' => 'cantidad', 'type' => 'number')
),
'rows' => array()
);
while($row = mysqli_fetch_assoc($sql))
{
$results = array(
'Topping' => $row['Topping'],
'cantidad' => $row['cantidad']
);
$results ['rows'][] = array('c' => array(
array('v' => $row['Topping']),
array('v' => $row['cantidad'])
));
}
$json = json_encode($results, JSON_NUMERIC_CHECK);
echo $json;
?>`
然后,我的图表的html代码:
<head>
<!--Load the AJAX API-->
<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.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
$.ajax({
url: 'http://localhost/cakesetup/pizza',
dataType: "json",
success: function (jsonData){
var data = new google.visualization.DataTable(jsonData);
// Set chart options
var options = {'title':'Distribucion de pizzas',
'width':800,
'height':600};
}
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
</div>
</div>
当我运行代码时,我得到的是#34; {&#34; Topping&#34;:&#34; Peperonni&#34;,&#34; cantidad&#34;:6,&#34 ;行&#34;:[{&#34; C&#34;:[{&#34; v&#34;:&#34; Peperonni&#34;},{&#34; v&#34;:6} ]}]}&#34;
提前致谢。
答案 0 :(得分:0)
检查您的网址
// Create the data table.
$.ajax({
url: 'http://localhost/cakesetup/pizza', // i dont think a url localhost will work. try cakesetup or /pizza
dataType: "json",
success: function (jsonData){
var data = new google.visualization.DataTable(jsonData);
// Set chart options
var options = {'title':'Distribucion de pizzas',
'width':800,
'height':600};
}
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
});