繁体   English   中英

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

[英]Undefined Reference Error when converting PHP variable to javascript variable

对于Internet编程,我们需要使用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。 感谢所有为解决我的问题做出贡献的人!

尝试这个:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM