PHP+ajax实现省市县三级联动

来源:互联网 发布:java log4j记录日志 编辑:程序博客网 时间:2024/04/30 13:38

//首页

<?php

header('content-type:text/html;charset=utf-8');
$conn=mysql_connect('localhost','root','')or die('数据库连接失败!');
mysql_select_db('test',$conn);
mysql_query('set names utf8');
$sql='select * from base_area where pid= 0';
$res=mysql_query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>省市县三级联动</title>
<script type="text/javascript" src="./jquery/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#one").change(function(){
$.ajax({
type:'get',
url:'two.php?ran='+Math.random()+"&oneId="+$(this).val(),
dataType:'html',
success:function(data){
$("#two").html(data);
}


})
})


})


</script>




<script type="text/javascript">
$(function(){
$("#two").change(function(){
$.ajax({
type:'get',
url:'three.php?ran='+Math.random()+"&twoId="+$(this).val(),
dataType:'html',
success:function(data){
$("#three").html(data);
}


})
})


})


</script>
</head>
<body>


<select id='one'>
<option value="-1">请选择省</option>
<?php
while($row=mysql_fetch_assoc($res))
{
?>
<option value="<?php echo $row['areaid'];?>"><?php echo $row['name'];?></option>
<?php
}
?>
</select>


<select id='two'>
<option value="-1">请选择市</option>
</select>


<select id='three'>
<option value="-1">请选择县</option>
</select>
</body>

</html>


//two.php

<?php
header('content-type:text/html;charset=utf-8');
    $oneId=$_GET['oneId'];
$conn=mysql_connect('localhost','root','')or die('数据库连接失败!');
mysql_select_db('test',$conn);
mysql_query('set names utf8');
$sql="select * from base_area where pid={$oneId}";
$result=mysql_query($sql);

?>
<?php
while($row=mysql_fetch_assoc($result))
{
?>
<option value="<?php echo $row['areaid'];?>"><?php echo $row['name'];?></option>
<?php
}
?>





//three.php
<?php
header('content-type:text/html;charset=utf-8');
    $twoId=$_GET['twoId'];
$conn=mysql_connect('localhost','root','')or die('数据库连接失败!');
mysql_select_db('test',$conn);
mysql_query('set names utf8');
$sql="select * from base_area where pid={$twoId}";
$result=mysql_query($sql);

?>
<?php
while($row=mysql_fetch_assoc($result))
{
?>
<option value="<?php echo $row['areaid'];?>"><?php echo $row['name'];?></option>
<?php
}
?>