我正在尝试使用 MYSQL 数据库中的数据显示 google 图表。当我使用两个单独的文件(php/js)但我想在一个文件中处理数据时,它就可以工作。
这是我得到的:
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Meter', 'type' => 'number')
);
$rows = array();
$select->execute();
while ($result = $select->fetch(PDO::FETCH_ASSOC)) {
$timestamp = strtotime($result['date']);
$date = date("d.m.Y - H:i", $timestamp);
$temp = array();
$temp[] = array('v' => $date);
$temp[] = array('v' => $result['meter']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$json = json_encode($table);
echo $json;
?>
<html>
<head>
<script type="text/javascript" src="../assets/js/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
dataType: "json",
async: true
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div2'));
chart.draw(data, {width: 1000, height: 240});
}
</script>
</head>
<body>
<hr class="major" />
<div id="chart_div2"></div>
</body>
</html>
PHP 数据已正确编码,但我不知道如何将数据“发送”到 javascript 部分。是否可以在同一个文件中接收 JSON 数据?
当我将 async: true
更改为 false
时,它只显示整个页面的代码,使用 true
则显示 undefined
.
亲切的问候, 斯卡尔
最佳答案
当你以这种方式回显 $json 时
<?php
// ...getting data
?>
<script>
var jsonData = <?php echo $json; ?>;
</script>
<?php
// rest of page...
稍后您可以在 javascript 中使用它,不再需要 ajax。
//....
chart.draw(jsonData, {width: 1000, height: 240});
//....
关于javascript - 从同一文件获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43115039/