簡體   English   中英

根據選擇的州顯示馬來西亞城市

[英]Show Malaysia cities based on states chosen

我想做一個馬來西亞的州和城市的下拉列表。

  • 這是我的初始頁面:(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)之間的狀態ID
    (2)如何根據在CODE HERE部分中選擇的狀態顯示城市下拉列表?

如我所見,您有兩種選擇:

1.)將整個對象加載到一個“大” JSON中,並用Javascript准備就緒-然后只需使用JS操作select即可。

2.)如果1號的表現不佳(biiiiig數據),則“惰性”加載選擇-再次使用AJAX-並使用JS進行渲染選擇。

所以-使用JS進行所有可能的操作,我認為這是最簡單的:)

ps:編寫用於渲染選擇的方法時-請仔細考慮所有可能的情況,並為其提供重置功能-最終將為您提供幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM