【问题标题】:How to concatenate multiple php variables within Javascript如何在 Javascript 中连接多个 php 变量
【发布时间】:2018-04-10 18:49:56
【问题描述】:

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

有谁知道我在这里做错了什么?

【问题讨论】:

  • PHP 完成渲染后该变量的外观应该如何?
  • 错误/问题是什么?
  • 变量应类似于“3334 South Shore Lane Cary, North Carolina 27519”
  • 我想我也忘了逗号
  • 我假设 restaurant_id 是 int 数据类型,在这种情况下不要在你的 SQL 中引用它。

标签: javascript php mysql concatenation


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    尝试添加逗号和空格。

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-19
        • 2018-11-06
        • 2012-07-29
        • 2017-08-21
        • 2011-11-30
        • 2011-11-03
        • 2014-07-28
        相关资源
        最近更新 更多