ajax 動態增加select下列選項框
來源:互聯網
上載者:User
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;
}
<?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";
}
?>
<script language="javascript" src="ajaxmenu.js"></script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>ajax2級聯動菜單示範</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>