gpt4 book ai didi

javascript - 在 HTML 中包含的 Javascript 中使用 PHP 变量

转载 作者:行者123 更新时间:2023-11-28 19:06:10 25 4
gpt4 key购买 nike

我想在Java脚本中使用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>

最佳答案

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

<?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 数组与您发布的完全相同,请将 php 更改为:

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

关于javascript - 在 HTML 中包含的 Javascript 中使用 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com