繁体   English   中英

未从php调用Javascript函数

[英]Javascript function not called from php

我正在一个网站上工作,在该网站上,我使用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>';
}
?>

尝试这个:

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

并将map_function移动到文档准备处理程序之外。

您尝试调用的函数在一个闭包中:DOM ready处理程序

无法从外部访问它。

搭上DOM ready处理程序。 如果您需要DOM准备就绪,则将调用方包装在被调用方上。

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

只是不要使用花括号,而是将代码放在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>

希望这个能对您有所帮助... :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM