简体   繁体   English

使用Json_encode将PHP数组传递给Javascript

[英]Passing PHP Array to Javascript with Json_encode

I am trying to pass a php array to a javascript variable as an object to use in google maps on the same page/file. 我试图将php数组作为对象传递给javascript变量,以便在同一页面/文件的google map中使用。 I am not able to send out an alert when testing the array in javascript. 在javascript中测试数组时,我无法发出警报。

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

var map;
        var Markers = {};
        var infowindow;
        var locations = '<?php echo json_encode($locations); ?>';
        var location = JSON.parse(loactions);
        alert(locations[0]);

I am getting this error 我收到此错误

Uncaught ReferenceError: loactions is not defined at account:299 未捕获的ReferenceError:在帐户:299上未定义活动

@Ghost is right. @鬼是正确的。 I did not notice that the $locations is inside while loop. 我没有注意到$ locations在while循环内。 So You should define $locations = []; 因此,您应该定义$locations = []; before while loop. 在while循环之前。 And then keep adding multiple records from while loop. 然后继续从while循环添加多个记录。 So the updated code should be like: 因此,更新后的代码应类似于:

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

And after this, you should put the JS code snippet. 然后,您应该放入JS代码段。

And use it like this: 并像这样使用它:

JS cpde: JS cpde:

var map;
var Markers = {};
var infowindow;
var locations = <?php echo json_encode($locations); ?>;
var location = JSON.parse(loactions);
alert(location.streetAddress);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM