class Map
{
public $Id;
public $longitudes;
public $latitudes;
public $lat_init;
public $lng_init;
public static function createMap($Id){
global $latitude, $longitude;
$dbh = Database::connect();
$query = "SELECT * FROM `cartes` WHERE Id=? ";
$sth = $dbh->prepare($query);
$sth->setFetchMode(PDO::FETCH_CLASS, 'Map');
$sth->execute(array($Id));
if ($sth->rowCount() === 0) return NULL;
$map=$sth->fetch();
$sth->closeCursor();
$lat=$map->latitudes;
$lng=$map->longitudes;
$latitude=unserialize($lat);
var_dump($latitude);
$longitude=unserialize($lng);
echo'<script type="text/javascript">'
,'var lat = json_encode($latitude);
var lng = json_encode($longitude);
draw(lat,lng);
'
,'</script>';
}
}
<?php
$dbh=Database::connect();
Map::createMap(6);
?>
当我执行这段代码时,出现以下错误:“$latitude is not defined”。 var_dump($latitude) 没问题。我认为脚本无法识别 $latitude 但我不知道为什么。有什么帮助吗? 谢谢
最佳答案
如果将其编码为 JSON,则需要将其正确地用引号引起来(不能在字符串中调用函数):
echo '<script type="text/javascript">
var lat = '. json_encode($latitude). ';
var lng = '. json_encode($longitude). ';
draw(lat,lng);
</script>';
关于javascript - 在 javascript 中使用 php 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22871766/