2014-03-05 90 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> 

希望这将帮助你... :)