我有以下代码片段,用于绘制饼图,其中 $valores 包含要在图中显示的值。此代码按预期工作
<?php
...
$valores = '';
foreach ($dados as $dado){
$valores .= "['$dado[estado] - $dado[numero]' , $dado[numero] ],";
}
$valores = substr($valores, 0, -1);
?>
...
<script type="text/javascript">
pizzaPlot();
function pizzaPlot(){
$(document).ready(function(){
plot2 = jQuery.jqplot('chart2',
[[ <?php echo $valores; ?> ]],
{
title: {
text: 'Parques Tecnológicos por Estado',
show: true,
textColor: 'black',
fontSize: 26
},highlighter: {
show: true,
formatString:'%s',
tooltipLocation:'sw',
useAxesFormatters:false
},
seriesDefaults: {
shadow: false,
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
startAngle: 180,
sliceMargin: 4,
showDataLabels: true }
},
legend: { show:true, location: 'w', tooltipContentEditor:'legenda' }
}
);
});
}
但是,当我将饼图绘制代码封装在名为 PizzaPlot() 的函数内时,不再绘制图表。下面的代码与前一个代码略有不同,现在 $valores 作为参数传递,而不是从脚本内部回显。
pizzaPlot("<?php echo $valores; ?> ");
function pizzaPlot(valores){
alert(valores);
$(document).ready(function(){
plot2 = jQuery.jqplot('chart2',
[[ valores ]],
{
title: {
text: 'Parques Tecnológicos por Estado',
show: true,
textColor: 'black',
fontSize: 26
},highlighter: {
show: true,
formatString:'%s',
tooltipLocation:'sw',
useAxesFormatters:false
},
seriesDefaults: {
shadow: false,
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
startAngle: 180,
sliceMargin: 4,
showDataLabels: true }
},
legend: { show:true, location: 'w', tooltipContentEditor:'legenda' }
}
);
});
}
从alert(valores)获取的消息与从echo $valores获取的消息相同
最佳答案
在你的第一个代码中,你会得到这个[[value of valores]]
。您可以将 valores 直接注入(inject)到代码中。在第二个代码中,您基本上执行以下操作:[["value of valores"]]
。这使用“value of valores”
作为字符串。
要解决问题,请使用此调用函数:
pizzaPlot([[<?php echo $valores; ?> ]]);
并删除函数内 valores 周围的括号。
关于javascript - 使用变量时使用 jQuery 绘图时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30466843/