[英]Difficulty in using php json_encode data received in javascript to display graph using chart.js library
I am trying to display a graph using chart.js javascript library. 我正在尝试使用chart.js javascript库显示图形。 The data I am fetching from database in PHP code and sending it to javascript by using json_encode()
method to get in js var from PHP. 我使用PHP代码从数据库中获取数据并将其发送到javascript,方法是使用json_encode()
方法从PHP获取js var。 The data actually is two fields of a table 'humidity' & 'temperature'. 数据实际上是表“湿度”和“温度”的两个字段。 After receiving the data in js, when I try to fetch 'humidity' & 'temperature' values from the js object I received, I get TypeError: jData is undefined
at line hum = jData.humidity;
在js中接收到数据之后,当我尝试从接收到的js对象中获取“湿度”和“温度”值时,出现TypeError: jData is undefined
在行hum = jData.humidity;
处TypeError: jData is undefined
hum = jData.humidity;
where jData is the parameter in js function receiving data from the script in PHP. 其中jData是js函数中的参数,该函数从PHP中的脚本接收数据。
I try to parse the jData to convert it into js object before fetching values but then I receive SyntaxError: JSON.parse: unexpected character
at line wData = JSON.parse(jData);
我尝试解析jData以在获取值之前将其转换为js对象,但随后我收到SyntaxError: JSON.parse: unexpected character
wData = JSON.parse(jData);
行上的SyntaxError: JSON.parse: unexpected character
wData = JSON.parse(jData);
. 。 Few posts on SO with same error tells that I the parse shouldn't be used as jData is already in js object form. 很少有SO出现相同错误的帖子告诉我,不应使用解析,因为jData已经以js对象的形式存在。
Here is my code: 这是我的代码:
php code: php代码:
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
js code: js代码:
function dspChrt(jData) { // to be called by loadChart() to render live chart
//wData = JSON.parse(jData);
hum = jData.humidity;
tem = jData.temperature;
humArray.shift();
humArray.push(hum);
temArray.shift();
temArray.push(tem);
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00'],
datasets: [{
label: 'Humidity',
data: humArray, // json value received used in method
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Temprature',
data: temArray,
backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}
With my previous experience on rendering the PHP json data inside JS, I could get it by rendering it as a string and then parse it. 根据我以前在JS中呈现PHP json数据的经验,我可以通过将其呈现为字符串然后进行解析来获取它。 Something like this. 这样的事情。
var WData = "'"+<?php echo json_encode($WData);?>+"'";
jData= JSON.parse(wData);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.