dongweng6241 2018-04-10 18:49
浏览 85
已采纳

如何在Javascript中连接多个php变量

Hello I am trying to utilize geomapping within in my website and I'm having trouble dynamically pulling the address for a restaurant and putting it into my javascript. I am using the get method to pull the restaurant_id from the url and then use this to pull the restaurant's complete address. This is the line of code I am having trouble with (var destinationAddress):

$con=mysqli_connect("root","");
        $rest_id2=$_GET['id'];
        $rest_id=(int)$rest_id2;
        $sql="SELECT * from restaurant WHERE restaurant_id='".$rest_id."'";
        $result=mysqli_query($con,$sql);
        $rows=mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
$(document).ready(function() {

    //exit early if no geolocation
    if(!navigator.geolocation) return;

    var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
</script>
</head>
....

Any one know see what I am doing wrong here?

  • 写回答

3条回答 默认 最新

  • duaj39673 2018-04-10 20:45
    关注

    Make your life easier: build the destination address outside of the template:

    $rows=mysqli_fetch_assoc($result);
    if( $rows !== NULL )
    {
        $destinationAddress = "{$rows['address']}, {$rows['city']}, {$rows['state']}, {$rows['zip']}";
    }
    else
    {
        // no rows! (anomaly)
        $destinationAddress = "no destination address available";
    }
    
    // due to the way you'll later inject the variable
    // into JavaScript code double quotes must be escaped
    
    $destinationAddress = str_replace( '"', '\"', $destinationAddress );
    

    Then simply

    $(document).ready(function() {
    
        //exit early if no geolocation
        if(!navigator.geolocation) return;
    
        var destinationAddress = "<?=$destionationAddress?>";
    } );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?