<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<?php
$con = mysqli_connect('localhost', 'root', '', 'Materniteti');
$f = "select count(*) as f from neonatologji where gjinia=1";
$m = "select count(*) as m from neonatologji where gjinia=2";
$result=$con->query($f);
$row = $result->fetch_assoc();
$f = $row["f"];
$resultati=$con->query($m);
$row1 = $resultati->fetch_assoc();
$m = $row1["m"];
?>
<script type="text/javascript">
$(document).ready(function () {
// Build the chart
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Statistikat e gjinise se bebeve'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: 'Vajza',
y: 22
}, {
name: 'Djem',
y: 6,
sliced: true,
selected: true
}]
}]
});
});
</script>
你好!有没有办法连接JavaScript与PHP,因为我需要$ f保存的值为这一个y:22和$ m而不是y = 6的值。我尝试使用json编码,但它没有工作或者我写错了但我无法解决这个错误。有人可以帮忙吗?
答案 0 :(得分:2)
非常简单直接地在php标签中回显变量。
如下所示。
<script type="text/javascript">
$(document).ready(function () {
// Build the chart
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Statistikat e gjinise se bebeve'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: 'Vajza',
y: '<?php echo $f; ?>'
}, {
name: 'Djem',
y: '<?php echo $m; ?>',
sliced: true,
selected: true
}]
}]
});
});
</script>
注意:只有当您的文件是php扩展名时,才能访问JS中的php变量。否则,您可以在具有php值的js中声明全局变量,并且可以在任何JS文件中访问。
答案 1 :(得分:0)
您可以将这些php值保存在隐藏的html输入标签中,例如
<input type ="hidden" id="var1" value="<?php echo $f;?>">
<input type ="hidden" id="var2" value="<?php echo $m;?>">
在javascript中我们可以通过
获取值var f = $('#var1').val();
var m = $('#var2').val();