ajax +php 二級聯動菜單代碼
<script language="javascript" >
var http_request=false;
function send_request(url){//初始化,指定處理函數,發送請求的函數
http_request=false;
//開始初始化XMLHttpRequest對象
if(window.XMLHttpRequest){//Mozilla浏覽器
http_request=new XMLHttpRequest();
if(http_request.overrideMimeType){//設置MIME類別
http_request.overrideMimeType("text/xml");
}
}
else if(window.ActiveXObject){//IE浏覽器
try{
http_request=new ActiveXObject("Msxml2.XMLHttp");
}catch(e){
try{
http_request=new ActiveXobject("Microsoft.XMLHttp");
}catch(e){}
}
}
if(!http_request){//異常,創建對象實例失敗
window.alert("創建XMLHttp對象失敗!");
return false;
}
http_request.onreadystatechange=processrequest;
//確定發送請求方式,URL,及是否同步執行下段代碼
http_request.open("GET",url,true);
http_request.send(null);
}
//處理返回信息的函數
function processrequest(){
if(http_request.readyState==4){//判斷對象狀態
if(http_request.status==200){//信息已成功返回,開始處理信息
document.getElementById(reobj).innerHTML=http_request.responseText;
}
else{//頁面不正常
alert("您所請求的頁面不正常!");
}
}
}
function getclass(obj){
var pid=document.form1.select1.value;
document.getElementById(obj).innerHTML="<option>loading...</option>";
send_request('doclass.php?pid='+pid);
reobj=obj;
}
</script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>ajax +php 二級聯動菜單代碼</title>
</head>
<body>
<form name="form1">
<select name="select1" id="class1" style="width:100;" onChange="getclass('class2');">
<option selected="selected"></option>
<option value="1">大類1</option>
<option value="2">大類2</option>
</select>
<select name="select2"id="class2" style="width:100;">
</select>
</form>
</body>
</html>
php 處理代碼
<?php
header("Content-type: text/html;charset=GBK");//輸出編碼,避免中文亂碼
$pid=$_GET['pid'];
$db=mysql_connect("localhost","root","7529639"); //創建數據庫連接
mysql_query("set names 'GBK'");
mysql_select_db("menuclass");
$sql="select classname from menu where parentid=".$pid."";
$result=mysql_query($sql);
//循環列出選項
while($rows=mysql_fetch_array($result)){
echo '<option>';
echo $rows['classname'];
echo "</option>n";
}
?>