2014-03-05 84 views
0

我正在一個網站上工作,其中我使用php從數據庫中檢索一些條目,並將它們顯示在屏幕上。現在,我想將其中一個列(地址)傳遞給javascript函數。從php調用Javascript函數

該函數將獲取變量並將其繪製在地圖上。我正在使用接收地址字符串並繪製它的Google地圖地理編碼。我需要通過將變量傳遞給它來調用函數。

我無法達到最終結果。事實上,javascript函數根本沒有被調用。我附加了javascript函數和調用java腳本函數的php代碼。因爲相當一段時間以來,我堅持在這裏和我焦急地等待解決

下面是代碼:

<script type="text/javascript"> 
$(document).ready(function(){ 
function map_function(addr){ 
    alert("function called with" + addr); 

    // Define the addresses we want to map. 
    var clubs = addr; 
    // Create a new Geocoder 
    var geocoder = new google.maps.Geocoder(); 
    // Locate the address using the Geocoder. 
    geocoder.geocode({ "address": clubs }, function(results, status) { 

     // If the Geocoding was successful 
     if (status == google.maps.GeocoderStatus.OK) { 

      // Create a Google Map at the latitude/longitude returned by the Geocoder. 
      var myOptions = { 
       zoom: 16, 
       center: results[0].geometry.location, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }; 

      var map = new google.maps.Map(document.getElementById("map"), myOptions); 

      // Add a marker at the address. 
      var marker = new google.maps.Marker({ 
       map: map, 
       position: results[0].geometry.location 
      }); 

     } else { 
       try { 
        console.error("Geocode was not successful for the following reason: " + status); 
       } catch(e) {} 
      } 
    }); 
} 
} 
</script> 
<?php 
$result = mysqli_query($con,$query); 
while($row = mysqli_fetch_array($result)) 
{ 
    $addr = $row['ADDRESS']; 
    echo '<script type="text/javascript">map_function({$addr});</script>'; 
} 
?> 

回答

0

試試這個:

echo '<script type="text/javascript">map_function("{$addr}");</script>'; 

並移動map_function文檔準備外處理程序。

+0

仍然沒有工作。警報沒有顯示。這意味着這個函數還沒有被調用。 :( – Jones

+0

您可以將map_function函數移動到文檔準備好處理函數之外嗎? – Ramesh

+0

是的,解決了這個問題,謝謝,但是現在,地圖一次只繪製一個元素,而不是保存之前的繪圖。 ?在該想法 – Jones

0

您嘗試調用的函數是在一個封閉:在DOM準備處理

這是不可能從外部訪問它。

獲取DOM準備好的處理程序。如果您需要準備好DOM,請將呼叫者包裹在被叫方上。

$(function(){ 
    map_function("{$addr}") 
}) 
+0

謝謝v很多。 :)但現在,地圖一次只繪製一個元素。這不是保存以前的繪圖。你有什麼想法嗎? – Jones

0

只是不要使用大括號,並將代碼放入onready函數。

最後把所有的php代碼放在script標籤裏面。像:

<?php 
$result = mysqli_query($con,$query); 

echo '$(document).ready(function(e) {'; 
while($row = mysqli_fetch_array($result)) 
{ 
    $addr = $row['ADDRESS']; 
    echo '<script type="text/javascript">map_function(\''.$addr.'\');</script>'; 
} 
echo '});'; 
?> 
</script> 

希望這將幫助你... :)