简体   繁体   English

如何使用PHP在JavaScript中定义变量

[英]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. 我正在开发一个应用程序,我想使用PHP代码定义一个javascript变量。 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;") . 在数据库中,我有3种类型的batiment点,并且我想变量geojson点具有3个值(我想变量var geojson_Point在几何"geometry" : echo $rslt;")中具有请求的所有结果"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 : 要从PHP定义javascript变量,请使用:

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

In your case a suggest to separate php & javascript codes like following : 在您的情况下,建议将phpjavascript代码分开,如下所示:

PHP : 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 : 将变量传递给javascript,如下所示:

JS : JS:

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

Hope this helps. 希望这可以帮助。

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

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