<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var newanswer = <?php echo"$newanswer"; ?>
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Monthly Progress Reports'
},
subtitle: {
text: 'Source: Sales Department'
},
xAxis: {
categories: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
},
yAxis: {
min: 0,
title: {
text: 'Range'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' Star';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: '5 Star', //Blue
data: [newanswer, 20, 30, 40, 50, 60, 70, 80, 90, 95, 10, 20]
}, {
name: '4 Star', //Red
data: [4, 20, 30, 40, 50, 60, 70, 80, 90, 95, 10, 20]
}, {
name: '3 Star', // Green
data: [3, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]
}, {
name: '2 Star', //violet
data: [2, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
}, {
name: '1 Star', //lightblue
data: [1, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
}]
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<?php
$newanswer = 50;
?>
</body>
</html>
这有可能将php值传递给javascript吗?我需要这样做,以便将mysql查询的值放入图中,并且该图由Java脚本编码。谢谢
问题是这条线
<?php $newanswer = 50; ?>
无法在此行上传递值:
var newanswer = <?php echo"$newanswer"; ?>
这样50的值就不会显示在此行中:
data: [newanswer, 20, 30, 40, 50, 60, 70, 80, 90, 95, 10, 20]
最佳答案
PHP没有JS的概念,因此您只需...
data: [<?php echo $newanswer ?>, 20, 30, 40, 50, 60, 70, 80, 90, 95, 10, 20]
但是,请注意,直接输出到JS代码块中意味着您必须格外小心,不要在JS代码中引入语法错误。一个错误,整个代码块被JS解析器杀死。因此,作为一般规则,您应该始终在PHP中使用json_encode()以确保生成语法上有效的JS。
即使您只是输出一个整数,这也适用-最好现在就进入json编码习惯。它将为您免去很多痛苦的事情:
data: [<?php echo json_encode($newanswer) ?>, 20, 30, 40, 50, 60, 70, 80, 90, 95, 10, 20]
因此,即使$ newanswer为null或未定义,您仍将使用valis JS。
关于php - 从PHP传递变量值到Javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12907319/