php之二級聯動下拉菜單

<script language = "JavaScript">   
var onecount;   
onecount=0;   
subcat = new Array();   
<?   
mysql_connect("localhost","root","");   
mysql_select_db( "test" );   
$sql = "select * from subject";   
$result = mysql_query( $sql );   
$count = 0;   
while($res = mysql_fetch_row($result)){   
?>   
subcat[<?=$count?>] = new Array("<?=$res[0]?>","<?=$res[1]?>","<?=$res[2]?>");   
<?   
$count++;   
}   
echo "onecount=$count;";   
?>   
//聯動函數   
function changelocation(locationid)   
{   
document.myform.ctype.length = 0;    
var locationid=locationid;   
var i;   
for (i=0;i < onecount; i++)   
       {   
         if (subcat[i][2] == locationid)   
         {    
   //var newOption1=new Option(subcat[i][1], subcat[i][0]);   
            //document.all.ctype.add(newOption1);   
            document.myform.ctype.options[document.myform.ctype.length] = new Option(subcat[i][1], subcat[i][0]);   
         }          
       }   
         
}    
</script>   
<form method="post" name="myform" action="ru_query.php">   
<select name="type" onChange="changelocation(document.myform.type.options[document.myform.type.selectedIndex].value)" size="1">   
<option selected value="">請指定主分類</option>   
         
<?   
$sql = "select * from depart";   
$result = mysql_query( $sql );   
while($res = mysql_fetch_row($result)){   
?>   
<option value="<? echo $res[0]; ?>"><? echo $res[1]; ?></option>   
   <? } ?>   
         
   </select>    
  
<select name="ctype">                   
       <option selected value="">請指定小分類</option>   
</select>   
<input type="submit" name="Submit" value="搜索">   
</form>   

 

 

數據庫是

表depart

departID departName

表subject

subjectID subjectName departID

1.通過精選取得數據庫的字段並且存入數組
2.定義自定義函數,遍歷數組並且使用echo命令把$參數轉化成js可以使用的變量
3.在js中使用<?自定義函數?>參數進行傳遞
4.通過js的new Option重新組織菜單選項

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章