[英]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&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.