在HTML中包含的Java脚本中使用PHP变量

时间:2015-07-25 19:40:58

标签: javascript php

我想在Java Script中使用PHP变量,我想获取从服务器上的mysql数据库读取的Select语句返回的经度和纬度变量。

这里有我的代码以及我尝试过的内容:

    <?php

...


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT Latitude, Longitude FROM mytable";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    $long = " ". $row["Longitude"]. "<br>";
    $lat = " ". $row["Latitude"]. "<br>";
    $latlong = " ". $row["Longitude"]. " , " . $row["Latitude"]. "<br>";
    echo $long;  //echo's -25.1234
    echo $lat; //echo's 25.1234
    echo $latlong; //echo's -25.1234 ,  25.1234
    }
} else {
    echo "0 results";
}
$conn->close();

?> 

<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Tracker</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script>
</head> 
<body>

  <div id="map" style="width: 1200px; height: 750px;"></div>

  <script language="JavaScript"> 

            var locations = [
              ['FirstColumnString<br/> SecondColumnString', -25.038326, 25.038326], //I would like to pass Lat Long from PHP code from above
            ];

        // I've tried
        //  ['FirstColumnString<br/>SecondColumnString', <?php echo $long; ?>, <?php echo $lat; ?>,
        //  ['FirstColumnString<br/>SecondColumnString', <?php echo $latlong ?>,
        //  ['FirstColumnString<br/>SecondColumnString', "<?php echo $long; ?>", <?php echo $lat; ?>,

...

  </script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您应首先将您的位置保存到数组中:

<?php

    $locations = Array();

    while($row = $result->fetch_assoc()) {
       $loc = Array("lat" => $row["Latitude"], "long" => $row["Longitude"]);
       $locations[] = $loc;
    }
?>

然后你可以将它传递给javascript:

<script>
var locations = <?php echo json_encode($locations) ?>;
// check what you've got:
console.log(locations);
</script>

然后您可以像这样访问您的值:

var firstLocationLatitude = location[0].lat;

如果你需要让你的js-array与你发布的内容完全一样,请将php更改为:

    $clmString = "FirstColumnString<br/> SecondColumnString";
    while($row = $result->fetch_assoc()) {
       $loc = Array($clmString,$row["Latitude"],$row["Longitude"]);
       $locations[] = $loc;
    }

答案 1 :(得分:1)

尝试替换

$long = " ". $row["Longitude"]. "<br>";
$lat = " ". $row["Latitude"]. "<br>";

$long = $row["Longitude"];
$lat = $row["Latitude"];

然后

var locations = [
    ['FirstColumnString<br/> SecondColumnString', <?php echo $long; ?>, <?php echo $lat; ?>],
];