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

时间:2021-06-16 09:50:57

I have seen many solutions to this question on this site. However, nothing I try seems to be working.

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

In my php file I have this:

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

In my javascript file I have this:

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

            }]
        });
    });

The javascript is a chart. I have been able to pass the info into the javascript file. I have used the alert() function and can see that it indeed brought the variable over. However, when I use the example variable in the javascript it does not work. Furthermore, if I copy over the alert results and replace data: example with data: [1, 1364, 1052, 922, 1, 1, 10, 1, 10, 10, 10, 265] then it works.

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

I can't understand why the variable example will not work but the chart works fine if you enter the info manually?

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

1 个解决方案

#1


5  

Try to remove quotes.

尝试删除引号。

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

#1


5  

Try to remove quotes.

尝试删除引号。

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