php中用ajax實現二級級聯(甚至多級級聯)
html中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
省份: < select name = "province_id" onChange = "getfid01(`showfid01`)" style = "border:1px solid #AEBBC4;width:150px;height:260px;" multiple>
< option value = "0" >--請選擇省份--</ option >
<? php
include(`../conn.php`);
$ sql = "select * from `table` order by `pid` desc" ;
$ query = mysql_query ($sql,$conn);
while($ row = mysql_fetch_array ($query)){
?>
< option value="<?php echo $row[`id`]?>"><? php echo $row[`title`]?></ option >
<? php
}
?>
</ select >
城市: < select name = "city_id" id = "showfid01" style = "border:1px solid #AEBBC4;width:150px;height:260px;" multiple></ select >
|
js程式碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
<script type= "text/javascript" >
<!-- var reobj = null ;
var http_request = false ;
if (window.XMLHttpRequest){
http_request= new XMLHttpRequest();
if (http_request.overrideMimeType){
http_request.overrideMimeType( "text/xml" );
}
} else if (window.ActiveXObject){
try {
http_request= new ActiveXObject( "Msxml2.XMLHttp" );
} catch (e){
try {
http_request= new ActiveXobject( "Microsoft.XMLHttp" );
} catch (e){}
}
}
function send_request(url){
if (!http_request){
window.alert( "建立XMLHttp物件失敗!" );
return false ;
}
http_request.open( "GET" ,url, true );
http_request.onreadystatechange=processrequest;
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 getfid01(obj){
var obj=obj;
var province_id=document.updoc2013.province_id.value;
document.getElementById(obj).innerHTML= "<option>loading...</option>" ;
send_request( "../ajax/get_city.php?province_id=" +province_id);
reobj=obj;
} //--> </script> |
後臺php程式碼(注意編碼必須是UTF-8,否則亂碼):
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php $province_id = $_GET [ `province_id` ];
if (! empty ( $province_id ) && $province_id != `0` ){
include ( `../conn.php` );
$sql = "select * from `city_table` where `fid`=`$province_id` order by `pid` desc" ;
$query =mysql_query( $sql , $conn );
while ( $row =mysql_fetch_array( $query )){
?> <option value= "<?php echo $row[`id`]?>" ><?php echo $row [ `title` ]?></option>
<?php }
}
?> |