您好,我正在尝试在我的网站中使用地理映射,但我在动态提取餐厅地址并将其放入我的 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?>";
} );
关于javascript - 如何在 Javascript 中连接多个 php 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49760968/