Javascript函数没有从php调用

时间:2014-03-05 13:21:18

标签: javascript php html5 google-maps

我正在一个网站上工作,我正在使用php从数据库中检索一些条目并在屏幕上显示它们。现在,我想将其中一个列(一个地址)传递给javascript函数。

该函数将接收变量并将其绘制在地图上。我正在使用谷歌地图地理编码,它接收地址字符串并绘制它。我需要通过传递一个变量从php调用该函数。

我无法达到最终结果。事实上,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>';
}
?>

3 个答案:

答案 0 :(得分:0)

试试这个:

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

将map_function移到文档就绪处理程序之外。

答案 1 :(得分:0)

您尝试调用的函数位于闭包中:DOM就绪处理程序

无法从外部访问它。

获取DOM就绪处理程序。如果您需要准备好DOM,请将调用者包装在被调用者身上。

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

答案 2 :(得分:0)

只是不要使用花括号并将代码放在onready函数中。

并且最后将所有php代码放在脚本标记中。像:

<?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>

希望这会对你有所帮助...... :)