【问题标题】:Show Malaysia cities based on states chosen根据所选州显示马来西亚城市
【发布时间】:2014-12-26 11:19:30
【问题描述】:

我想做一个马来西亚的州和城市下拉列表。

  • 这是我的初始页面:(test3.php)

  • 当我选择KL时,我对城市的期望输出如下:

  • 当我选择雪兰莪时,我对城市的期望输出如下:

  • 状态数据 json ($stateJsonObject)

    Array ( [0] => stdClass Object ( [stateId] => s1 [stateName] => Kuala Lumpur) 
    [1] => stdClass Object ( [stateId] => s2 [stateName] => Selangor))
    
  • 城市数据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 ))
    
  • 代码(test3.php)

    <html>
    <head>
    <script type="text/javascript">
        function showCity()
        {
            //state id from drop down list
            var stateId = state.options[state.selectedIndex].value;
    
            //CODE HERE
        }
    </script>
    </head>
    
    <body>
        <form action="test3.php" method="post">
        State:
        <select name="state" id="state" onchange="showCity();">
            <option value ="">select one</option>
            <?php
                for($i = 0; $i < count($stateJsonObject); $i++)
                {
                    echo '<option value = '.$stateJsonObject[$i] -> stateId.'>';
                    echo $stateJsonObject[$i] -> stateName;
                    echo '</option>';
                }
            ?>
        </select>
    
        <br />
    
        City:
        <select name="city" id="city">
            <option value ="">select one</option>
        </select>
    </form>
    </body>
    </html>
    
  • 基于以上参考,以下是我的问题:
    (1) 如何比较 CODE HERE 部分的 js 和 php (json) 之间的 state id
    (2) 如何根据我在CODE HERE上选择的state显示城市下拉列表 部分?

【问题讨论】:

    标签: javascript php json curl


    【解决方案1】:

    我可以看到你有两个选择:

    1.) 在一个“大”JSON 中加载整个对象并在 Javascript 中准备好它 - 然后只需使用 JS 操作选择。

    2.) 如果第一个表现不佳(biiiiig 数据)“惰性”加载选择 - 再次使用 AJAX - 并使用 JS 呈现选择。

    所以 - 使用 JS 进行所有可能的操作,我认为这是最简单的 :)

    p.s.:在编写渲染选择的方法时 - 好好考虑所有可能的场景,并为它们设置一个重置功能 - 最后它会帮助你:)

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多