将php变量传递给外部javascript文件

时间:2014-04-08 02:20:51

标签: javascript php variables

我在这个网站上看到过很多关于这个问题的解决方案。但是,我尝试的任何东西似乎都没有用。

在我的php文件中,我有这个:

<?php
$monthlycalories = "[1, 1364, 1052, 922, 1, 1, 10, 1, 10, 10, 10, 265]";
?>

<script type="text/javascript">
  var test = "<?php echo $monthlycalories; ?>"; 
</script>

在我的javascript文件中,我有这个:

$(function () {
var example = test;
alert(example);
        $('#monthly').highcharts({
            chart: {
                type: 'column'
            },
            title: {
                text: 'Monthly Calorie Intake'
            },
            xAxis: {
                categories: [
                    'Jan',
                    'Feb',
                    'Mar',
                    'Apr',
                    'May',
                    'Jun',
                    'Jul',
                    'Aug',
                    'Sep',
                    'Oct',
                    'Nov',
                    'Dec'
                ]
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Calories'
                }
            },
            tooltip: {
                headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                pointFormat: '<tr><td style="color:{series.color};padding:0"></td>' +
                    '<td style="padding:0"><b>{point.y:.1f} Calories</b></td></tr>',
                footerFormat: '</table>',
                shared: true,
                useHTML: true
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
            series: [{
                name: 'Months',
                data: example

            }]
        });
    });

javascript是一张图表。我已经能够将信息传递到javascript文件中。我使用了alert()函数,可以看到它确实带来了变量。但是,当我在javascript中使用example变量时,它不起作用。此外,如果我复制警报结果并将data: example替换为data: [1, 1364, 1052, 922, 1, 1, 10, 1, 10, 10, 10, 265],那么它可以正常工作。

我无法理解为什么变量example不起作用,但如果手动输入信息,图表工作正常?

1 个答案:

答案 0 :(得分:6)

尝试删除引号。

var test = <?php echo $monthlycalories; ?>; 
相关问题