exampleUsingPHP.html
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var jsonData = $.ajax({
url: "getData.php",
//dataType:"java",
async: false
//success: function(results) {alert(results);}
}).responseText;
// 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() {
alert(jsonData);
// Create our data table out of JSON data loaded from server.
var data = google.visualization.arrayToDataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
<script>
</script>
</html>
getData.php
<?php
echo "[['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]";
?>
所以我的问题是线...
var data = google.visualization.arrayToDataTable(jsonData);
当我尝试将jsonData传递到arrayToDataTable()时,它不喜欢它是字符串。如何将字符串“ jsonData”转换为可在arrayToDataTable()函数中使用的有效JavaScript?
最佳答案
或者,您可以仅使用功能json_encode()
获得无压力的结果。创建一个由值组成的数组(当然,要构建一个数组以使其适合Google图表),然后使用该函数。 Sample Demo
PHP(getData.php)
if(isset($_POST['get_chart'])) {
$values = array(
array('Task', 'Hours Per Day'),
array('Work', 11),
array('Eat', 2),
array('Commute', 2),
array('Watch TV', 2),
array('Sleep', 7),
);
echo json_encode($values);
exit;
}
HTML / jQuery
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(load_chart_data);
function load_chart_data() {
$.ajax({
url: 'getData.php', // provide correct url
type: 'POST',
data: {get_chart: true},
dataType: 'JSON', // <-- since youre expecting JSON
success: function(chart_values) {
console.log(chart_values); // take a peek on the values (browser console)
draw_chart(chart_values); // call your drawing function!
}
});
}
function draw_chart(chart_values) {
var data = google.visualization.arrayToDataTable(chart_values);
var options = {
title: 'Your super chart!',
vAxis: {title: 'Hours Per Day', titleTextStyle: {italic: false}},
hAxis: {title: 'Task', titleTextStyle: {italic: false}},
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>