Ajax三级联动
全国省市县查询
html代码
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script src="../jquery-1.11.2.min.js"></script> <script src="sanji.js"></script> </head> <body> <h1>区域查询</h1> <div id="sanji"></div> </body> </html>
js代码实现各区市随省的变化而变化
$(document).ready(function(e) { $("#sanji").html("<select id='sheng'></select><select id='shi'></select><select id='qu'></select>");//将三个下拉的字符串交给前边的div tiansheng();//加载省的数据 tianshi();//加载市的数据 tianqu();//加载区 的数据 $("#sheng").change(function(){//变化后执行 tianshi();//重新加载市 tianqu();//重新加载区 }) $("#shi").change(function(){//变化后执行 tianqu();//加载区的数据 }) }); function tiansheng(){ var pcode = "0001"; //找出省的父级代号 $.ajax({ async:false,//同步加载 url:"states.php", data:{pcode:pcode}, type:"POST", dataType:"TEXT", success: function(data){ var hang = data.split("|");//拆分行 var str = ""; for(var i=0;i<hang.length;i++){ var lie = hang[i].split("^");//拆分列 str += "<option value='"+lie[0]+"'>"+lie[1]+"</option>"; } $("#sheng").html(str); } }); } function tianshi(){ var pcode = $("#sheng").val();//找市的父级代号,省选中项的值 $.ajax({ async:false,//同步加载 url:"states.php", data:{pcode:pcode}, type:"POST", dataType:"TEXT", success: function(data){ var hang = data.split("|"); var str = ""; for(var i=0;i<hang.length;i++){ var lie = hang[i].split("^"); str += "<option value='"+lie[0]+"'>"+lie[1]+"</option>"; } $("#shi").html(str); } }); } function tianqu(){ var pcode = $("#shi").val();//找区的父级代号,市选中项的值 $.ajax({ url:"states.php", data:{pcode:pcode}, type:"POST", dataType:"TEXT", success: function(data){ var hang = data.split("|"); var str = ""; for(var i=0;i<hang.length;i++){ var lie = hang[i].split("^"); str += "<option value='"+lie[0]+"'>"+lie[1]+"</option>"; } $("#qu").html(str); } }); }
处理页面
<?php $pcode = $_POST["pcode"]; require "DBDA.class.php"; $db = new DBDA(); $sql = "select * from chinastates where parentareacode='{$pcode}'"; echo $db->strquery($sql);
DBDA封装功能
<?php class DBDA{ public $host="localhost"; //服务器地址 public $uid="root"; //用户名 public $pwd="123"; //密码 public $dbname="crud"; //数据库名称 public function query($sql,$type=0){ $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname); $result = $db->query($sql); if($type){ return $result; }else{ return $result->fetch_all(); } } public function strquery($sql,$type=0){ $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname); $result = $db->query($sql); if($type){ return $result; }else{ $arr = $result->fetch_all(); $str =""; foreach($arr as $v){ $str .= implode("^",$v)."|"; } $str = substr($str,0,strlen($str)-1); return $str; } } }