如何在min.js文件中嵌入php代码

时间:2018-06-26 06:24:44

标签: javascript php chart.js

我正在使用JavaScript库chartjs创建图表。为此,我有一个引导模板,其中包含带有图表的chart.min.js文件,但是这些图表不是由数据库中的数据构建的。因此,如何将我的php代码嵌入该min.js文件中,以用图表替换图表。我需要通过数据库表中的数据来构建它们。这是引导程序模板中的代码,即chart.min.js文件:

Chart.defaults.global.defaultFontFamily='-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif',
Chart.defaults.global.defaultFontColor="#292b2c";var ctx=document.getElementById("myAreaChart"),
myLineChart=new Chart(ctx,{
	type:"line",
	
	data:{labels:["Mar 10","Mar 2","Mar 3","Mar 4","Mar 5","Mar 6","Mar 7","Mar 8","Mar 9","Mar 10","Mar 11","Mar 12","Mar 13"],
	datasets:[{label:"Sessions",
	lineTension:.3,
	backgroundColor:"rgba(2,117,216,0.2)",
	borderColor:"rgba(2,117,216,1)",
	pointRadius:5,
	pointBackgroundColor:"rgba(2,117,216,1)",
	pointBorderColor:"rgba(255,255,255,0.8)",
	pointHoverRadius:5,
	pointHoverBackgroundColor:"rgba(2,117,216,1)",
	pointHitRadius:20,
	pointBorderWidth:2,
	data:[1e4,30162,26263,18394,18287,28682,31274,33259,25849,24159,32651,31984,38451]}]},
	options:{scales:{xAxes:[{time:{unit:"date"},
	gridLines:{display:!1},ticks:{maxTicksLimit:7}}],
	yAxes:[{ticks:{min:0,max:4e4,maxTicksLimit:5},
	gridLines:{color:"rgba(0, 0, 0, .125)"}}]},legend:{display:!1}}})

这是我要在该min.js文件中替换的代码:

<?php
$dbhost='localhost';
$dbname='chartjs';
$dbuser='root';
$dbpass='';
try{
	$dbcon=new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
	$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
	die($ex->getMessage());
}
$stmt=$dbcon->prepare("SELECT * FROM chartjs");
$stmt->execute();
$json=[];
$json2=[];
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
	extract($row);
	$json[]=$title;
	$json2[]= (int)$amounts;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Charts</title>
</head>
<body>
	<div style="height: 50%">
<canvas id="myChart"></canvas></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<script type="text/javascript">
	var ctx = document.getElementById('myChart').getContext('2d');
	ctx.height = 100;
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: <?php echo json_encode($json); ?>,
        datasets: [{
            label: "Amounts per Title",
            backgroundColor: 'grey',
            borderColor: 'black',
            data: <?php echo json_encode($json2); ?>,
        }]
    },

    // Configuration options go here
    options: {

    }
});
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

它不是那样工作的,您没有将php嵌入到javascript中,相反,您将js嵌入了php文件中。

PHP在服务器中运行,并且以html(+ js + css)的形式提供给客户端,无论您想以哪种方式呈现它(包括Chart.min),都应将min.js包含在php文件中。 .js