国、州、市の3つのドロップダウンリストがあります。
国リストでの選択に基づいて州リストにデータを入力し、州リストでの選択に基づいて都市リストにデータを入力したい。
これが私がこれを試みた方法です
国リストから、onchageイベントを使用してjavaスクリプト関数を呼び出します。
<select name="country" id="id1" onchange="onCountryChange(this.value)">
次に、国に関連付けられている州の名前を取得するようにサーバーにリクエストを送信します。
function onCountryChange(str){ if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("statenames").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","./view/countrychange.php?countryname="+str,true); xmlhttp.send(); }
次のコードを使用して状態の値を取得します。
<?php $countryname=$_GET["countryname"]; $connection = pg_connect("host=localhost port=5432 dbname=STAGE2 user=postgres password=jssate"); if (!$connection){ echo "<H1>Error in connection to Database</H1>"; echo "<H2>Please try again</H2>."; } else{ $query1="Select distinct(state) from master_table where country='$countryname'"; $result = pg_query($connection,$query1); $numrows = pg_numrows($result); if ($numrows>0){ echo "State <select name="state" id="stateid">; for ($row_index=0;$row_index<$numrows;$row_index++) { $state_name=pg_result($result,$row_index,0); echo "<option value="$state_name\">$state_name</option>"; } echo "</select>"; } } pg_close($connection); ?>
3.クライアント側で次のコードを使用して結果を表示しました。
<div id="statenames">
//Original select list placed here is replaced by the one returned by server.
</div>
これは私にとってはうまくいき、州は国名に基づいて入力されます。次に、3番目のリストにデータを入力するにはどうすればよいですか。状態リストを表示するために選択したアプローチは正しいですか?私は今取得している状態の選択リストを制御できないので。