在test.js文件中使用php变量

时间:2014-03-21 17:25:37

标签: javascript php

我已将javascript文件的文件扩展名更改为.php。这是我在 index.html 中的代码:

<script type="text/javascript" src="test.php"></script>

我使用

修正了test.php之上的标题
  <?php
        header("Content-type: text/javascript");
$test=50; ?>
// my javascript

    var lineChartData = {
        labels : ["test1","test2","test3","test4","test4","test6","test7"],
        datasets : [
            {
                fillColor : "rgba(220,220,220,0.5)",
                strokeColor : "rgba(220,220,220,1)",
                pointColor : "rgba(220,220,220,1)",
                pointStrokeColor : "#fff",
                data : [<?PHP echo test; ?>,59,90,81,56,55,40]
            },
            {
                fillColor : "rgba(151,187,205,0.5)",
                strokeColor : "rgba(151,187,205,1)",
                pointColor : "rgba(151,187,205,1)",
                pointStrokeColor : "#fff",
                data : [28,48,40,19,96,27,100]
            }
        ]

    };

我无法在javascript data : [<?PHP echo test; ?>,59,90,81,56,55,40]

中传递php varibale

任何帮助?

2 个答案:

答案 0 :(得分:0)

你的文件有错误的语法。它应该是:

<?php
    header("Content-type: text/javascript");
?>
// my javascript
var lineChartData = {
    labels : ["test1","test2","test3","test4","test4","test6","test7"],
    datasets : [
        {
            fillColor : "rgba(220,220,220,0.5)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            data : [65,59,90,81,56,55,40]
        },
        {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            data : [28,48,40,19,96,27,100]
        }
    ]

};

答案 1 :(得分:0)

使用Heredoc

您需要打印文本。

使用以下内容包围您的javascript:

echo <<<EOD

Javascript goes here

EOD;