简体   繁体   中英

How to get php while loop inside javascript

I am struggling with the solution of this problem.

I have a php file and a javascript while.

My php file looks like this:

<?php
$sql = "SELECT * FROM flats";
$result = $conn->query($sql);

if ($result->num_rows > 0) 
// output data of each row
while($row = $result->fetch_assoc()) {  
$flat_id = $row["flat_id"];                 
$price = $row["price"];                     
$address = $row["address"];
$bedrooms = $row["bedroom"];
$maxguests = $row["maxguests"];
$area = $row["area"];
$lat = $row["lat"];
$lng = $row["lng"];

$map_flats = "{
    title : 'Property',
    image : '1-1-thmb.png',
    type : 'For Sale',
    price : '$price',
    address : '$address',
    bedrooms : '$bedrooms',
    bathrooms : '$maxguests',
    area : '$area',
    position : {
        lat : $lat,
        lng : $lng
    },
    markerIcon : 'marker-green.png'
},";



echo $map_flats;


    }}

 else {
    echo "0 results";
}

$conn->close();
?>

And i want to show the content of the $map_flats inside the js.

var flats = [$map_flats];

Could you please help me how could I make it working?

Thanks in advance,

Tibor.

JavaScript would need the structure in JSON format, and it needs to be echo ed to the output. Something like this:

var flats = <?php echo json_encode($map_flats); ?>;

Though it looks like your $map_flats isn't actually a PHP object, but an already formatted JSON string? It would likely be easier to use PHP objects in server-side code and JSON in client-side code, but if you don't need to JSON-encode the output then you can just echo it as-is:

var flats = <?php echo $map_flats; ?>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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