将PHP变量传递给外部JavaScript文件

3

我在这个网站上看过很多关于这个问题的解决方案。然而,我尝试的一切似乎都不起作用。

在我的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变量时,它不起作用。此外,如果我复制alert结果并将data: example替换为data: [1, 1364, 1052, 922, 1, 1, 10, 1, 10, 10, 10, 265],则它可以工作。
我无法理解为什么变量example不起作用,但手动输入信息后,图表可以正常工作?

1
请查看您浏览器中生成的源代码。 - Felix Kling
1个回答

6

尝试移除引号。

var test = <?php echo $monthlycalories; ?>; 

哇,谢谢@sectus!我简直不敢相信那就是问题所在。我花了几个小时来解决这个问题。再次感谢! - MagentoMan
1
如上所述:探索您的页面源代码。 - sectus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接