我正在尝试将 php 数组作为对象传递给 javascript 变量,以便在同一页面/文件的谷歌地图中使用。在 javascript 中测试数组时,我无法发出警报。
PHP
while( $row = $query->fetch_assoc() ){
$street_address = $row['street_address'];
$zip = $row['zip'];
$state = $row['state'];
$lat = $row['lat'];
$lng = $row['lng'];
$test = $row['sellerDB_test'];
$firstName = $row['first_name'];
$lastName = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
/* Each row is added as a new array */
$locations = array( 'streetAddress'=>$street_address, 'state'=>$state, 'zip'=>$zip, 'lat'=>$lat, 'lng'=>$lng, 'test'=>$test, 'first name'=>$firstName, 'last name'=>$lastName, 'email'=>$email, 'phone'=>$phone);
JS
var map;
var Markers = {};
var infowindow;
var locations = '<?php echo json_encode($locations); ?>';
var location = JSON.parse(loactions);
alert(locations[0]);
我收到这个错误
Uncaught ReferenceError: loactions is not defined at account:299
最佳答案
@Ghost 是对的。我没有注意到 $locations 在 while
循环中。所以你应该在 while 循环之前定义 $locations = [];
。
然后继续从 while 循环中添加多条记录。所以更新后的代码应该是这样的:
$locations = [];
while( $row = $query->fetch_assoc() ){
$street_address = $row['street_address'];
$zip = $row['zip'];
$state = $row['state'];
$lat = $row['lat'];
$lng = $row['lng'];
$test = $row['sellerDB_test'];
$firstName = $row['first_name'];
$lastName = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
/* Each row is added as a new array [] */
$locations[] = array( 'streetAddress'=>$street_address, 'state'=>$state, 'zip'=>$zip, 'lat'=>$lat, 'lng'=>$lng, 'test'=>$test, 'first name'=>$firstName, 'last name'=>$lastName, 'email'=>$email, 'phone'=>$phone);
}
在此之后,您应该放置 JS 代码片段。
然后像这样使用它:
JS 代码:
var map;
var Markers = {};
var infowindow;
var locations = <?php echo json_encode($locations); ?>;
var location = JSON.parse(loactions);
alert(location.streetAddress);
关于javascript - 使用 Json_encode 将 PHP 数组传递给 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707863/