js兩級聯動其實網上還是有很多代碼可以找的。最關鍵的問題在於數組數據的讀取。
這裏運用了getJSON從php獲取數據,然後php讀mysql數據庫。
js代碼:
<script> var aProvince = new Array(); var aProvinceID = new Array(); var aCity = new Array(); var aCityID = new Array(); function init() { var request = ""; var c1 = new Array(); var c1ID = new Array(); var c2 = new Array(); var c2ID = new Array(); $.getJSON("js_data.php",request,function(response){ $.each(response.data, function(i) { c1[i] = response.data[i].name; c1ID[i] = response.data[i].id; c2[i] = new Array(); c2ID[i] = new Array(); $.each(response.data[i].data, function(j) { c2[i][j] = response.data[i].data[j].name; c2ID[i][j] = response.data[i].data[j].id; }); }); aProvince = c1; aProvinceID = c1ID; aCity = c2; aCityID = c2ID; //alert(aProvince); loadProvince(); loadCity(0); }); } function loadProvince() { for(var i=0; i<aProvince.length; i++){ $("select#selChapter").append("<option value='"+aProvinceID[i]+"'>"+aProvince[i]+"</option>"); } $("select#selChapter").append("<option value=\"-1\" class=\"addChapter\">新增一章</option>"); $("select#selChapter").change(function(){ var obj = document.getElementById("selChapter"); var index = obj.selectedIndex; if(obj.options[index].value != -1) { $("select#selSection").html(""); loadCity(index); } }) } function loadCity(index) { for(var i=0; i< aCity[index].length; i++) { $("select#selSection").append("<option value='"+aCityID[index][i]+"'>"+aCity[index][i]+"</option>"); } $("select#selSection").append("<option value=\"-1\" class=\"addSection\">新增一節</option>"); } </script>
select標籤:
<tr> <td>所屬章</td> <td><select id="selChapter" name="chapterId"> </select> <input class="newChapter" name="newChapter" type="text" value="請輸入新章標題" onFocus="if(!this._haschanged){this.value=''};this._haschanged=true;"/> </td> </tr> <tr> <td>所屬節</td> <td><select id="selSection" name="sectionId"> </select> <input class="newSection" name="newSection" type="text" value="請輸入新節標題" onFocus="if(!this._haschanged){this.value=''};this._haschanged=true;"/> </td> </tr>
php代碼:
<?php $return_data = Array(); require_once('../database_config.php'); $sql = "select Chap_No,Title from chapter"; $sqlf = mysql_query($sql); if($sqlf && mysql_num_rows($sqlf) > 0) { $i = 0; while(($info = mysql_fetch_object($sqlf))) { $return_data['data'][$i]['id'] = $info->Chap_No; $return_data['data'][$i]['name'] = $info->Title; $j = 0; $sql1 = "select Sect_No,Title from section where Chap_Id=".$info->Chap_No; $sqlf1 = mysql_query($sql1); while(($info1 = mysql_fetch_object($sqlf1))) { $return_data['data'][$i]['data'][$j]['id'] = $info1->Sect_No; $return_data['data'][$i]['data'][$j]['name'] = $info1->Title; $j++; } $i++; } $return_data['status'] = 1; } else { $return_data['status'] = 5; } echo json_encode($return_data); ?>