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

标签 javascript php mysql concatenation

您好,我正在尝试在我的网站中使用地理映射,但我在动态提取餐厅地址并将其放入我的 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/

相关文章:

javascript - 等待异步函数

php - 在文本框中输入时不显示自动完成功能,但值显示在控制台中

php - 表单未提交到数据库

javascript - Three.js为行星添加高分辨率纹理的方法

Javascript 功能在我的正则表达式上无法正常工作

javascript - Gatsby - 警告尝试导入错误 : 'css' does not contain a default export (imported as 'styles' )

javascript - 单击按钮后如何编辑特定 td 中的值

java - 如何从多个本地网站提取信息?

MySQL 分布式数据库,每个节点都有 mysql 访问权限

mysql - Rails 如何使用另一个表中的数据在 seeds.rb 中的表中播种