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

plicqrtu  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(342)

你好,我试图利用geomapping在我的网站,我有麻烦动态拉一个餐厅的地址,并把它放到我的javascript。我使用get方法从url中提取餐厅的id,然后使用这个方法提取餐厅的完整地址。这是我遇到问题的代码行(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>
....

有人知道我做错了什么吗?

0g0grzrc

0g0grzrc1#

使您的生活更轻松:在模板之外构建目标地址:

$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 );

那就简单点

$(document).ready(function() {

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

    var destinationAddress = "<?=$destionationAddress?>";
} );
vxqlmq5t

vxqlmq5t2#

尝试添加逗号和空格。

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

y4ekin9u3#

因为你忘了关闭函数 }) ,试试看

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

相关问题