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=proces-s-request;
http_request.send( null );
} function proces-s-request(){
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 }
}
?> |