将城市名称从php传递给js(第2部分)

时间:2014-10-31 06:38:57

标签: javascript php json

续在Show Malaysia cities based on states chosen

  • 城市数据json ($ cityJsonObject

    Array ( [0] => stdClass Object ( [cityId] => c1 [cityName] => Kajang [cityStateId] 
    => s2 ) [1] => stdClass Object ( [cityId] => c2 [cityName] => Seputeh 
    [cityStateId] => s1 ) [2] => stdClass Object ( [cityId] => c3 [cityName] => Shah 
    Alam [cityStateId] => s2 ) [3] => stdClass Object ( [cityId] => c4 [cityName] => 
    Klang [cityStateId] => s2 ) [4] => stdClass Object ( [cityId] => c5 [cityName] => 
    Kepong [cityStateId] => s1 ))
    
  • 代码(cityName)

    <?php
        for($i = 0; $i < count($cityJsonObject); $i++)
        {
            echo $cityJsonObject[$i]->cityName;
    
            //PASS VARIABLE TO JS
        }
    ?>
    
    <script type="text/javascript">
        //GET VARIABLE FROM PHP AND DISPLAY CITY NAME
    </script>
    
  • 从上面的代码中,我可以得到以下内容:

    Kajang 
    Seputeh
    Shah Alam
    Klang
    Kepong
    
  • 我的问题是如何将上述城市名称传递给变量并传递给js?我应该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用json_encode并输出一个字符串,该字符串将通过javascript轻松解析

试试此代码

<?php
    $array_to_js = array();

    for($i = 0; $i < count($cityJsonObject); $i++)
    {
        $array_to_js[] = $cityJsonObject[$i]->cityName;
    }
?>

<script type="text/javascript">
    //GET VARIABLE FROM PHP AND DISPLAY CITY NAME
    var js_array = <?php echo json_encode($array_to_js, JSON_HEX_QUOT) ?>;
</script>

答案 1 :(得分:0)

<?php

echo '<script type="text/javascript">';

// your php code here maybe you can need json_encode(), I'm not sure I get what you mean.
echo json_encode($cityJsonObject);
echo '<script>';
?>