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条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器