您好,我正在尝试在网站中利用地理映射,但无法动态提取餐厅的地址并将其放入我的JavaScript中。我正在使用get方法从URL中拉出restaurant_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>
....


有人知道我在这里做错了吗?

最佳答案

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

$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?>";
} );

10-08 04:41