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

时间:2014-11-03 21:14:07

标签: javascript php json google-maps

对于互联网编程分配,我们需要使用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>

当我在Google Chrome浏览器中呈现网页时,出现以下控制台错误消息:

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。感谢所有为解决我的问题做出贡献的人!

1 个答案:

答案 0 :(得分:0)

试试这个:

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

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