2013-11-26 127 views
-2

我沒有太多的編程經驗。
我有一些我正在適應的代碼,我不明白變量是如何從PHP傳遞到JavaScript的。我懷疑我錯過了一些基本理論,但迄今爲止我一直無法在網絡上追蹤它。谷歌地圖標記信息被傳遞如下: -

使用Javascript的PHP變量

<?php 
$mrk_cnt = 0;  
while ($obj = $res->fetch_object()){ 
    $username[$mrk_cnt] = $obj->username; 
    $inf[$mrk_cnt] = $obj->title; 
    $lat[$mrk_cnt] = $obj->lat; 
    $lng[$mrk_cnt] = $obj->long; 
    $begin[$mrk_cnt] = $obj->begin; 
    $end[$mrk_cnt] = $obj->end; 
    $distance[$mrk_cnt] = $obj->distance; 
    $marker_type[$mrk_cnt] = $obj->type; 
    $icon[$mrk_cnt]=(($marker_type[$mrk_cnt]=='inquirer')? 'red_marker': 'blue_marker');  
$mrk_cnt++;  
} 
?> 

而且上有一些JavaScript的PHP的呼應: -

<script> 
<?php 
    for ($lcnt = 0; $lcnt < $mrk_cnt; $lcnt++){ 
     echo "var point$lcnt = new google.maps.LatLng($lat[$lcnt], $lng[$lcnt]);\n"; 
     echo "var mrktx$lcnt = \"$inf[$lcnt]\";\n"; 
     echo "var infowindow$lcnt = new google.maps.InfoWindow({ content: mrktx$lcnt });"; 
     echo "var marker$lcnt = new google.maps.Marker({position: point$lcnt, map: map, icon:" . $icon[$lcnt] . "});\n"; 
     echo "google.maps.event.addListener(marker$lcnt,'click', function() {infowindow$lcnt.open(map,marker$lcnt);});\n"; 
     echo "bounds.extend(point$lcnt);\n";  
    } 
?> 
    map.fitBounds(bounds); 
} 
</script> 

如何是PHP變量 - $緯度[],例如 - 找到他們的方式進入JavaScript?它們是用PHP聲明的,它們不被連接或引用。假設JavaScript會知道$ lat [$ lcnt]將會是在$ php中聲明的$ lat [$ mkr_cnt],$ lcnt設置爲= $ mkr_cnt。
非常感謝。

回答

0

您給出的第二塊代碼實際上是這樣做的:將javascript回顯到您的頁面,javascript不關心它是來自PHP還是任何其他語言,通過在腳本中回顯html/javascript代碼,您正在提供將在該頁面下運行的JavaScript的信息,PHP僅用於從API中檢索數據,然後安裝將使其在瀏覽器中工作的JavaScript。

關於PHP單/雙引號另一個方便的信息: What is the difference between single-quoted and double-quoted strings in PHP?

+0

謝謝,這是我缺少的信息的重要一點。我發現這個頁面對我來說很清楚:http://hydrogen.informatik.tu-cottbus.de/wiki/index.php/PHP_Variable_Interpolation – user2790911