数据库dt_area中表的数据结构:
html代码部分:
省:<select name="" id="sheng" onChange="selshi(this)"> ???<option value="">请选择</option> ???</select>市:<select name="" id="shi" onChange="selqu(this)"> ???<option value="">请选择</option></select>区:<select name="" id="qu"> ???<option value="">请选择</option></select
js代码部分:
//用来放chulidata函数里面的新数组 ???var attr = []; ???//页面加载完成后调用函数sendInfo,给函数传了个省下拉框的id ???window.onload = function(){ ???????sendInfo(‘sheng‘); ???} ???//页面加载完成后调用的函数(code=0页面加载完成后先将省的信息显示到页面),type就是传过来的select的id,code是以get方式向php页面传的area_parent_id ???function sendInfo(type,code=0){ ???????//创建对象 ???????var xhr = new XMLHttpRequest(); ???????//监听ajax状态 ???????xhr.onreadystatechange = function(){ ???????????if(xhr.readyState==4){ ???????????????//处理数据,调用函数chulidata,传的两个参数xhr.responseText(从php页面查询的数据库数据,形式为:110000,北京;120000,天津;) type select的id ???????????????chulidata(xhr.responseText,type); ???????????} ???????} ???????//创建一个新的http请求:以get的方式访问php页面, ???????xhr.open("get",‘sanjiliandong.php?code=‘+code); ???????//发送请求 ???????xhr.send(null); ???} ???//处理数据的函数,data:xhr.responseText(从php页面查询的数据库数据) type:select的id ???function chulidata(data,type){ ???????//将从php页面查询的数据进行处理,去掉分隔符; 组成一个一维数组,形式为: [ "110000,北京", "120000,天津"] ???????var arr1 = data.split(‘;‘), ???????????//定义一个变量:一个option标签 ???????????str = "<option value=‘‘>请选择</option>"; ???????//遍历数组 ???????for(var i=0;i<arr1.length;i++){ ???????????//将数组中每个原素中的逗号去掉,组成的attr数组形式为:[[ "110000", "北京" ] , [ "120000", "天津" ]] ???????????attr[i] = arr1[i].split(‘,‘); ???????????//将attr数组里的元素放到str的option标签中 ???????????str += "<option value=‘"+attr[i][0]+"‘>"+attr[i][1]+"</option>"; ???????} ???????//将str放到相应的页面位置显示 ???????document.getElementById(type).innerHTML = str; ???} ???//在选择省时调用的函数,obj是调用函数时传过来的this ???function selshi(obj){ ???????//在选择省时将区里面的内容清空 ???????var str = "<option value=‘‘>请选择</option>"; ???????document.getElementById(‘qu‘).innerHTML = str; ???????//将市的select标签的id和相应省标签的value值在调用函数sendInfo时传过去 ???????sendInfo(‘shi‘,obj.value); ???} ???//选择市时调用的函数 ???function selqu(obj){ ???????//将区的select标签的id和相应市标签的value值在调用函数sendInfo时传过去 ???????sendInfo(‘qu‘,obj.value); ???}
php代码部分:
<?php$db = new MySQLi(‘localhost‘,‘root‘,‘‘,‘dt_area‘);!mysqli_connect_error() or die(‘链接错误‘);$db->query(‘set names utf8‘);//以get方式提交过来的code,也就是数据库表中的area_parent_id$code = $_GET[‘code‘];//数据库查询,条件是area_parent_id等于sendInfo函数里面的xhr.open请求传过来的code值$sql = ‘select id,area_name from dt_area where area_parent_id = ‘.$code;$res = $db->query($sql);$arr = $res->fetch_all();$str = "";//for循环将查询得到的$arr数组,变成 110000,北京;120000,天津 这样的形式foreach($arr as $key=>$value){ ???foreach($value as $v){ ???????$str.=$v.","; ???} ???//去掉110000,北京,120000,天津, 最后面的逗号 ???$str = substr($str,0,-1); ???//110000,北京;120000,天津; ???$str.= ‘;‘;}//去掉110000,北京;120000,天津; 最后面的分号$str = substr($str,0,-1);//最后输出 110000,北京;120000,天津echo $str;
省市区三级联动 用ajax实现
原文地址:https://www.cnblogs.com/wfc139/p/9015625.html