我想使用以下代码以图形的形式从mysql中检索数据。但是,没有显示任何内容。有人能帮助我吗?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "graphdata.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
<?php
echo("<div id='chart_div'></div>");
?>
这是我的getdata.php
:
$sql = "SELECT count(`booth_number`),`sold_by` FROM `registration1` where week(`Date`) = week(curdate()) GROUP BY `sold_by`";
$result = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'string')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
echo json_encode($data);
答案 0 :(得分:1)
如前所述,我认为您需要在成功回调中移动代码:
function drawChart() {
$.ajax({
url: "graphdata.php",
type: "GET",
dataType:"json",
success: function(jsonData, textStatus, jqXHR) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
});
}
[edit]可以在jsBin找到一个工作示例(包含一些模拟数据)。
[edit2]使用重复问题中提供的输出更新jsBin上的示例:
{
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"string"
}
],
"rows": [
{
"c":[
{"v":"3"},
{"v":"jaspreet singh "}
]
},{
"c":[
{"v":"3"},
{"v":"joseph swanson"}
]
}
]
}
服务器返回的JSON是错误的,对象应如下所示:
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"number"
}
],
"rows": [
{
"c":[
{"v":"jaspreet singh "},
{"v":"3"}
]
},{
"c":[
{"v":"joseph swanson"},
{"v":"3"}
]
}
]
};
现在所需的改变应该是显而易见的。希望这会有所帮助。
[edit3] getdata.php
应包含以下代码段imho:
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'number')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array(
'c' => array(
array('v' => $row[1]),
array('v' => $row[0])
)
);
}