将PHP变量转换为javascript变量时出现未定义的引用错误


Undefined Reference Error when converting PHP variable to javascript variable

对于互联网编程任务,我们需要使用PHP解析.json文件中的数据。

以下是我从文件中获取文本的php代码:

$pointsA = json_decode(utf8_encode(file_get_contents("pointsA.json")), true);
$pointsB = json_decode(utf8_encode(file_get_contents("pointsB.json")), true);
$mapCenter = utf8_encode(file_get_contents("center.json"));

这是我试图将其传递给javascript的代码。

    <script type="text/javascript">
        var mapCenter, aMatches, bMatches;
        mapCenter = <?php echo $mapCenter;?>;
        aMatches = <?php echo json_encode($aMatches);?>;
        bMatches = <?php echo json_encode($bMatches);?>;
    </script>

最后一个块位于html代码的中,并且位于所使用的任何其他代码之前。特别是,头部看起来像这样:

<head>
    <title>Route Plotting</title>
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script type="text/javascript">
        var mapCenter, aMatches, bMatches;
        mapCenter = <?php echo $mapCenter;?>;
        aMatches = <?php echo json_encode($aMatches);?>;
        bMatches = <?php echo json_encode($bMatches);?>;
    </script>
    <script
        type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAdt2pyYUsR8xq7n_0InalSC7mahTk6Hcg&amp;libraries=places">
    </script>
    <script
        type="text/javascript"
        src="googleMapsCalendar.js">
    </script>
</head>

当我在谷歌浏览器中渲染网页时,我会收到以下控制台错误消息:

Uncaught SyntaxError: Unexpected token var index.php:12
Uncaught ReferenceError: mapCenter is not defined

第一条错误消息的行号不正确,因为它会导致注释。我相信这是在谈论我发布的第一个标签中的第一行。

第二条错误消息指向这段代码:

var mapCenterLoaction = new google.maps.LatLng(mapCenter['center']['lat'], mapCenter['center']['lat']);

这是我尝试在外部javascript文件中使用"mapCenter"变量的第一个地方。

如有任何帮助,我们将不胜感激。

编辑:

这是通过检查头中的第一个元素生成的代码:

        var mapCenter, aMatches, bMatches;
        mapCenter = var center=
{
    "center": { "lat" : "44.974", "long" : "-93.234" },
    "zoom": "15"
};
        aMatches = [0];
        bMatches = [0];

这是否意味着我在定义这些时不需要"var"关键字,而只需要在中呼应它们?

如果是这种情况,我如何在外部javascript文件中引用这些变量?

第二次编辑:

问题是,我正在解析的文件,我认为是json,实际上是javascript。感谢所有为解决我的问题做出贡献的人!

试试这个:

mapCenter = '<?php echo $mapCenter;?>';

我认为您收到此错误是因为$mapCenter为空。