php无法在javascript中运行

时间:2018-05-27 10:47:35

标签: javascript php mysql

以下代码无法正常使用

<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 - 假设&#39; pointLat&#39; (这将在PHP的未来版本中引发错误。)

和pointLng相同。

请帮忙。

2 个答案:

答案 0 :(得分:1)

只需将数组索引放在引号中(如果您确定在行中有 pointLat pointLong (在调试之前可以使用var_dump $ row))< / p>

<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++;
    }

答案 1 :(得分:-1)

您是否尝试将正确的内容类型添加到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.