PHP+Ajax三种方法实现省市县三级联动实现省、市、县三级联动是一个最典型、最常用的一个ajax应用案例,当用户
PHP+Ajax三种方法实现省市县三级联动
实现省、市、县三级联动是一个最典型、最常用的一个ajax应用案例,当用户选择省的时候出现了该省的所有的市;当用户选择市的时候出现了该市所有的县,那么将怎样实现这样的三级联动的效果呢?我们不妨做个简单的分析:
想要实现省市县三级联动效果并不难,假设数据库中已经有一个地区的表了,里面存储所有的省市县的信息,实现思路:
1) 初始化所有的省份,这个可以直接从数据库中查询出来省份
2)当用户选择省份的时候触发事件,把当前的省份的id通过ajax发出请求传递到服务端的程序中
3)服务端根据客户端的请求,查询数据库,并按照一定的格式返回给客户端
4)客户端获取服务端的数据,进行必要的处理显示出来
服务端的程序根据id查询后,把结果可以封装成多种格式,比如:html 、特殊字符串、Json格式等,下面我们来看下每一种格式都是如何实现的:
第一种:服务端返回 html格式的情况
客户端请求页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>3G开发者联盟-ajax-html.html</title></head><body><select id="sheng" onchange="getArea(this.value,'shi')" ></select> 省 <select id="shi" onchange="getArea(this.value,'xian')" ></select> 市 <select id="xian" ></select> </body></html><script language="javascript" type="text/javascript">function getArea(id,p){//初始化ajaxvar xhr = new XMLHttpRequest();var url = "./area-html.php?id="+id+"&r="+Math.random();//打开请求xhr.open("get",url,true);//发送数据xhr.send(null);//等待响应xhr.onreadystatechange = function (){.if(xhr.readyState == 4){document.getElementById(p).innerHTML = xhr.responseText;}} //响应的结果直接放到对应的下拉菜单中}//加载所有的省份getArea("",'sheng')</script>
服务端返回html标签代码:
<?php header("Content-Type:text/html;charset=UTF-8");//连接数据库include("../include/dbconn.php");//根据用户返回的ID查询$id=$_GET['id'];$sql="select id,name from area where id like '".$id."__'";$rs=mysql_query($sql);//将查询的结果封装成html标记//echo mysql_num_rows($rs);echo "<option value='0'>请选择</option>";while($rows=mysql_fetch_assoc($rs)){echo '<option value=\''.$rows['id'].'\'>'.$rows['name'].'</option>';}?>
上述效果火狐下没有问题,但是服务器返回html代码的弊端是 document.getElementById(p).innerHTML = xhr.responseText;这句话在IE下有问题,IE不识别下拉菜单的innerHTML属性
第二种:服务器返回 自定义的 字符串 客户端通过 拆分字符串实现效果
客户端代码如下:
1.<?php2.header("Content-Type:text/html;charset=UTF-8");3.//连接数据库4.include("../include/dbconn.php");5.//根据用户返回的ID查询6.$id=$_GET['id'];7.$sql="select id,name from area where id like '".$id."__'";8.$rs=mysql_query($sql);9.//将查询的结果封装成html标记10.//echo mysql_num_rows($rs);11.//echo "<option value='0'>请选择</option>";12.echo ":";13.while($rows=mysql_fetch_assoc($rs)){14.15.echo ';'.$rows['id'].':'.$rows['name'];16.17.}18.19.?>
第二种方法实现起来比较容易理解,而且能够兼容IE和火狐 ,如果新手的话建议使用此种方法
第三种 :服务器端返回Json数据格式,客户端解析Json产生Json对象,实现省市县
三级联动效果
客户端代码:
1.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">2.<html xmlns="http://www.w3.org/1999/xhtml">3.<head>4.<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />5.<title>无标题文档</title>6.</head>7.8.<body>9.10.<select id="sheng" onchange="getArea(this.value,'shi')" ></select> 省 <select id="shi" onchange="getArea(this.value,'xian')" ></select> 市 <select id="xian" ></select> 11.</body>12.</html>13.<script language="javascript" type="text/javascript">14.15.function getArea(id,p){16.17.//初始化ajax18.var xhr = new XMLHttpRequest();19.var url = "./area-json3.php?id="+id+"&r="+Math.random();20.var sel=document.getElementById(p);21.//打开请求22.xhr.open("get",url,true);23.24.//发送数据25.xhr.send(null);26.27.//等待响应28.xhr.onreadystatechange = function (){29.30.if(xhr.readyState == 4){31.32.var jsonstr=xhr.responseText;33.//alert(jsonstr);34.//清空下拉菜单35.sel.length=0;36.37.var obj=eval("("+jsonstr+")")38.//alert(obj.citys.length);39.40.for(var i=0;i<obj.citys.length;i++){41.42.43.//产生一个option对象44.var opt=new Option(obj.citys[i].name,obj.citys[i].id);45.//添加到当前列表当中46.sel.add(opt,null);47.48.}49.50.}51.52.53.} 54.//响应的结果直接放到对应的下拉菜单中55.56.}57.58.//加载所有的省份59.getArea("",'sheng')60.</script>
服务端代码:
[php] view plaincopyprint?
- 1. <?php 2. header("Content-Type:text/html;charset=UTF-8");
- 3. //连接数据库 4. include("../include/dbconn.php");
- 5. //根据用户返回的ID查询 6. $id=$_GET['id'];
- 7. $sql="select id,name from area where id like '".$id."__'"; 8. $rs=mysql_query($sql);
- 9. //将查询的结果封装成Json数据格式 10.
- 11. //$str= '{"ctiys":[{"id":"11","name":"北京"},{"id":"13","name":"河北"}]}'; 12. //$arr= json_decode($str,true); //将字符串转换为json数组
- 13. //echo $arr['ctiys'][1]['name']; 14.
- 15. //$arr2=array("aa"=>"张三","bb"=>123); 16. //$str2= json_encode($arr2); //将数组转换为json字符串
- 17. //echo $str2; 18. //定义一个数组用于存放数据库中查询到得每一条数据
- 19. $arr =array(); 20. /*
- 21. 整体封装为这样的一个数组:22. arr2(
- 23. 'cities'=>array(24. 0=>array( 'id'=>'', 'name'=>'' )
- 25. 1=>array( 'id'=>11, 'name'=>'北京市' )26. 2=>array( 'id'=>12, 'name'=>'天津市' )
- 27. ……28. )
- 29. )30. 这个数组转换为json字符串就成为这种形式:
- 31. {'cities':[{'id':'', 'name':''}, {'id':'11', 'name':'北京市'}, {'id':'12', 'name':'天津市'}, ……]}32. 拼装为json对象obj后,就可以通过obj.cities[0].id等形式访问对应的值了
- 33. */ 34.
- 35. while($rows=mysql_fetch_assoc($rs)){ 36. //构建一个二维数组,每一个元素是一个对象(一条记录)$arr将构建str的[{"id":"11","name":"北京"},{"id":"13","name":"河北"}]部分
- 37. $arr[]=$rows; 38. }
- 39. //重新产生新的数组构建 $arr将构建{"ctiys":[{"id":"11","name":"北京"},{"id":"13","name":"河北"}]} 40. $arr2 =array('citys'=>$arr);
- 41. echo json_encode($arr2); 42. ?>