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

Mag*_*Man 3 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>
Run Code Online (Sandbox Code Playgroud)

在我的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

            }]
        });
    });
Run Code Online (Sandbox Code Playgroud)

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

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

sec*_*tus 6

尝试删除引号.

var test = <?php echo $monthlycalories; ?>; 
Run Code Online (Sandbox Code Playgroud)