Javascript中的Php变量

时间:2014-11-28 20:27:17

标签: javascript php

我正在创建一个圆环图,我遇到麻烦的是我的所有数据都被拉到了服务器端。这是带有设定值的图表的html。我如何将我的php变量作为值回显?

<html>
<head>
<script src="Chart.js"></script>
<style>
body{
padding: 0;
margin: 0;
}
#canvas-holder{
width:25%;
}
</style>
</head>
<body>
<div id="canvas-holder">
<canvas id="chart-area" width="500" height="500"></canvas>
</div>
<script>
var doughnutData = [
{
value: 500,
color:"#941616",
highlight: "#FF0000",
label: "Needs Agreement"
},

{
value: 500,
color: "#575757",
highlight: "#777777",
label: "Pre-Production"
},

{
value: 500,
color: "#aaaaaa",
highlight: "#cccccc",
label: "In Production"
}
];
window.onload = function(){
var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
};
</script>
</body>
</html>

我的php代码通过api获取需要的数据,然后将每个值存储在变量中,例如。

<?php
$needs_agreement = 148000;
$pre_produciton = 137000;
$in_production = 3678000;
?>

同样,回显php变量的最佳方法是什么,其中value:高于?

更新:

var doughnutData = [
{
value: <?php echo $needs_agreement ?>,
color:"#941616",
highlight: "#FF0000",
label: "Needs Agreement"
},

{
value: <?php echo $pre_production ?>,
color: "#575757",
highlight: "#777777",
label: "Pre-Production"
},

{
value: <?php echo $in_production ?>,
color: "#aaaaaa",
highlight: "#cccccc",
label: "In Production"
}
];

建议作为答案的上述代码不起作用。

2 个答案:

答案 0 :(得分:2)

没有什么可以阻止你在javascript中间回显PHP变量。

<script>
var doughnutData = [
{
value: <?php echo $some_data ?>,
color:"#941616",
highlight: "#FF0000",
label: "Needs Agreement"
}
</script>

在将文档发送到浏览器之前处理所有PHP,因此javascript将在客户端执行时完成。

答案 1 :(得分:0)

我终于得到了它的工作,在我的php文件的最后:

echo '<script>' . 'var zx =' . $total_need . '</script>';
echo '<script>' . 'var zy =' . $total_pre . '</script>';
echo '<script>' . 'var zz =' . $total_in . '</script>';

html部分将如下所示:

var doughnutData = [
{
value: zx,
color:"#941616",
highlight: "#FF0000",
label: "Needs Agreement"
},

{
value: zy,
color: "#575757",
highlight: "#777777",
label: "Pre-Production"
},

{
value: zz,
color: "#aaaaaa",
highlight: "#cccccc",
label: "In Production"
}
];