简体   繁体   中英

How can I define variable in javascript using PHP

I am developing an application and I would like to define a javascript variable using PHP code. In a database I have in 3 points from the type batiment and I would that the variable geojson point had 3 value (I would that the variable var geojson_Point have all the result of the request in the geometry "geometry" : echo $rslt;") .

var geojson_Point = 
{
    <?php 
    $query = "SELECT ST_ASGeoJSON(geometry) FROM poi where type='batiment'";  
    $result = pg_query($con, $query);
    while ($row = pg_fetch_assoc($result))  
    {  
        foreach($row as $rslt);
            "type": "Feature",
            "properties": { },
            "geometry":
        echo $rslt; 
    } 
    ?>;
}

To define javascript variable from PHP use :

var JS_variable = <?php echo $PHP_variable; ?>;

In your case a suggest to separate php & javascript codes like following :

PHP :

$result_array = array();

while ($row = pg_fetch_assoc($result))  
{  
    foreach($row as $rslt){
        $geojson_point = array("type" => "Feature", "properties" => "{}", "geometry" => $rslt);

        array_push($result_array, $geojson_point);
    }
}

Pass the variable to javascript like following :

JS :

var geojson_point = <?php echo json_encode($result_array); ?>;

Hope this helps.

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