我有一个带有数组输出的php文件,我想将其发送到javascript文件。我使用$get()
创建了一个函数,但是我不知道如何在data.addRows
下反映。我用console.log(data2)
进行了调试,但看到了数组,但不知道如何在addRows
下反映输出。
data.php:
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "
['".$row['time']."',".$row['temp'].",".$row['hum']."],";
}
}
?>
script.js:
google.charts.load('current', {'packages':['corechart', 'line']});
google.charts.setOnLoadCallback(drawLineColors);
function drawLineColors() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'time');
data.addColumn('number', 'Temperature');
data.addColumn('number', 'Humidity');
$.get('data.php').then(function(data2){
///I made here console.log(data2) and I got the array like this
['2019-05-13 00:25:13',27.20,41.00],['2019-05-13 00:26:00',27.20,41.00],
data.addRows([//I want to know how to reflected here!]);
let rowIndex = data.getNumberOfRows() - 1;
let lastTime = data.getValue(rowIndex, 0);
let lastTemp = data.getValue(rowIndex, 1);
let lastHum = data.getValue(rowIndex,2);
答案 0 :(得分:2)
不要使用字符串连接而是使用JSON构建数组。
将json-encode用作:
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = array($row['time'], $row['temp'], $row['hum']);
}
echo json_encode($data);
然后在JS文件中,您可以将JSON.parse用作:
obj = JSON.parse(data2);
data.addRows(obj);