頁面上有兩個 select 下拉框,一個對應「學院」,一個對應「專業」。要求選擇學院後,顯示該學院的相關信息,同時專業下拉框只列出屬於該學院的專業名稱——也就是典型的二級聯動效果。
思路是:在兩個 select 上分別綁定 onchange 事件,事件內用 Ajax 的 GET 方法把選中值提交給後端 PHP,再把查詢結果輸出到頁面對應區域。
<script type="text/javascript">
var XmlHttp;
function createXmlHttpRequestObject(){
if(window.ActiveXObject){ // 判斷是否 IE 內核
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{ // Chrome、Firefox 等非 IE 內核
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(xmlHttp){
return xmlHttp;
}else{
alert("對象創建失敗,請檢查浏覽器是否支持 XMLHttpRequest!");
}
}
// 學院下拉框事件
function showCollegeInfo(){
var selectIndex = document.getElementById("college").selectedIndex;
var value = document.getElementById("college").options[selectIndex].value;
if(value){
createXmlHttpRequestObject();
var url = "college.php?xy=" + value;
url = encodeURI(url);
xmlHttp.onreadystatechange = ajaxok;
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
document.getElementById("collegeinfo").style.display = "block";
}else{
document.getElementById("collegeinfo").style.display = "none";
}
}
function ajaxok(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
document.getElementById("collegeinfo").innerHTML = xmlHttp.responseText;
}
}
// 專業下拉框事件
function showMajorInfo(){
var selectIndex = document.getElementById("major").selectedIndex;
var value = document.getElementById("major").options[selectIndex].value;
if(value){
createXmlHttpRequestObject();
var url = "major.php?zy=" + value;
url = encodeURI(url);
xmlHttp.onreadystatechange = ajaxok2;
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
document.getElementById("majorinfo").style.display = "block";
}else{
document.getElementById("majorinfo").style.display = "none";
}
}
function ajaxok2(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
document.getElementById("majorinfo").innerHTML = xmlHttp.responseText;
}
}
</script>
後端 college.php 與 major.php 分別根據傳入的學院值、專業值查詢並輸出對應信息即可。核心在於:每次選擇變化都重新請求,並把返回內容寫入相應 div。