gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:32:48 25 4
gpt4 key购买 nike

续。上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 ))
  • 代码(城市名称)

    <?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?我应该怎么做?

最佳答案

您可以使用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>

关于javascript - 将城市名称从 php 传递到 js(第 2 部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26668815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com