嗨,我的 php 文件中有这个数组变量
$data_chart=[95,65,25,12,458,896,325];
我创建了一个脚本如下
<script>
var data = <?php echo json_encode($data_chart); ?>;
</script>
我如何将数据变量传递到我的chart-data.js文件中?(无需将变量嵌入html标签中)
最佳答案
既然你像这样使用 php,相关的 javascript 就必须与 canvas 元素位于同一个 html 文档中。以下内容改编自 chart.js
documentation here 。像这样的事情可能会起作用:
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'type',
data: {
labels: ["1", "2", "3", "4", "5", "6", "7"],
datasets: [{
label: 'my data',
data: <?php echo json_encode($data_chart); ?>,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderWidth: 1
}]
}
});
</script>
如果你确实无法将javascript嵌入到html文件中,那么你可以通过html文件将php数据存储在本地存储中,然后读取javascript文件,但这似乎不必要地困难。
关于javascript - 将 php 变量传递给 Chart.js 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40665819/