php无法在javascript中工作

hjzp0vay  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(293)

下面的代码工作不正常

<script type="text/javascript">
function initMap(){
    var center = {lat:9.93,lng:76.9}
    var mapOption = {zoom: 10,center: center,/*center: new google.maps.LatLng(9.93,76.9)*/};
    var markerOptions ={position:center};
    //create map
    var map = new google.maps.Map(document.getElementById('map'),mapOption);

    //create marker
    //var loc_pat = new google.maps.Marker(markerOptions);
    //loc_pat.setMap(map);
    <?php 
        $sql = "SELECT * FROM mappoints";
        $result = mysqli_query($con,$sql);
        while($r = mysqli_fetch_array($result)){
            echo '  var myLatlng1 = new google.maps.LatLng('.$row[pointLat].', '.$row[pointLong].');';
        }
    ?>

}

它抛出错误:
警告:使用未定义的常量pointlat-假定为“pointlat”(这将在将来的php版本中引发错误)。
点也一样。
请帮忙。

cgvd09ve

cgvd09ve1#

您是否尝试过向php添加正确的内容类型?

<?php
// definition of Content Type
@header("Content-type: application/javascript");

// define a simple variable
text= "Hello world!"; 
?>
alert('<?php echo $text; ?>'); // Javascript code, printing php code.
relj7zay

relj7zay2#

只需将数组索引放在引号中(如果您确定在行中有pointlat和pointlong(您可以在调试之前varïdump$row))

<script type="text/javascript">
function initMap(){
    var center = {lat:9.93,lng:76.9}
    var mapOption = {zoom: 10,center: center,/*center: new google.maps.LatLng(9.93,76.9)*/};
    var markerOptions ={position:center};
    //create map
    var map = new google.maps.Map(document.getElementById('map'),mapOption);

//create marker
//var loc_pat = new google.maps.Marker(markerOptions);
//loc_pat.setMap(map);
<?php 
    $sql = "SELECT * FROM mappoints";
    $result = mysqli_query($con,$sql);
    while($r = mysqli_fetch_array($result)){
        echo '  var myLatlng1 = new google.maps.LatLng('.$row['pointLat'].', '.$row['pointLong'].');';
    }
?>

}

当然,您的解决方案是有缺陷的,因为您只定义了一个变量 var myLatlng1 如果$row返回多个结果,你只需要最后一个,最好把它们放在一个列表中,我的意思是

echo '  var myLatlng =[]';
     $i = 0 ;
    while($r = mysqli_fetch_array($result)){
        echo 'myLatlng[' . $i . '] = new google.maps.LatLng('.$row['pointLat'].', '.$row['pointLong'].');';
        $i++;
    }

相关问题