簡體   English   中英

Javascript中的PHP變量

[英]Php variables inside Javascript

我正在創建一個甜甜圈圖,而我遇到麻煩的是我的所有數據都被拉到了服務器端。 這是帶有設置值的圖表的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;
?>

同樣,在value:上面的位置上回顯php變量的最佳方法是什么?

更新:

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"
}
];

被建議作為答案的上述代碼不起作用。

沒有什么能阻止您簡單地在javascript中間回顯PHP變量。

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

所有PHP都會在將文檔發送到瀏覽器之前進行處理,因此javascript將在客戶端執行時完成。

我終於使它工作了,在我的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" } ]; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM