<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ajax</title> <script> window.onload=function(){ var xhr=new XMLHttpRequest(); xhr.open(‘get‘,‘index.php?type=sheng‘,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ var data=eval(xhr.responseText); var str=‘<option value="0">--请选择省--</option>‘; for(var i=0; i<data.length; i++){ str+=‘<option value="‘+data[i].provinceID+‘">‘+data[i].province+‘</option>‘; } document.getElementById(‘province‘).innerHTML=str; //console.log(data[0].province); //alert(data); } } xhr.send(); //市 var province = document.getElementById(‘province‘); province.onchange=function(){ var value=this.value; xhr.open(‘get‘,‘index.php?type=shi&provinceID=‘+value,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ var data=eval(xhr.responseText); var str=‘<option value="0">--请选择市--</option>‘; for(var i=0; i<data.length; i++){ str+=‘<option value="‘+data[i].cityID+‘">‘+data[i].city+‘</option>‘; } document.getElementById(‘city‘).innerHTML=str; } } xhr.send(); } //县 var area = document.getElementById(‘city‘); city.onchange=function(){ var value=this.value; xhr.open(‘get‘,‘index.php?type=area&cityID=‘+value,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ var data=eval(xhr.responseText); var str=‘<option value="0">--请选择县--</option>‘; for(var i=0; i<data.length; i++){ str+=‘<option value="‘+data[i].areaID+‘">‘+data[i].area+‘</option>‘; } document.getElementById(‘area‘).innerHTML=str; } } xhr.send(); } } </script> </head> <body> <select id="province"> <option value="0">--请选择省--</option> </select> <select id="city"> <option value="0">--请选择市--</option> </select> <select id="area"> <option value="0">--请选择县--</option> </select> </body> </html>
<?php $servername = "127.0.0.1"; $username = "root"; $password = "root"; // 创建连接 $mysqli = new mysqli($servername, $username, $password); // 检测连接 if ($mysqli->connect_error) { die("连接失败: " . $mysqli->connect_error); } $mysqli->select_db(‘three‘); $mysqli->query(‘set names utf8‘); if($_GET[‘type‘]==‘sheng‘){ $list=$mysqli->query(‘select * from jing_province‘); while($row=$list->fetch_array()){ $data[]=$row; } echo json_encode($data); }elseif($_GET[‘type‘]==‘shi‘){ $father=$_GET[‘provinceID‘]; $list=$mysqli->query(‘select * from jing_city where father=‘.$father.‘ ‘); while($row=$list->fetch_array()){ $data[]=$row; } echo json_encode($data); }else if($_GET[‘type‘]==‘area‘){ $father=$_GET[‘cityID‘]; $list=$mysqli->query(‘select * from jing_area where father=‘.$father.‘ ‘); while($row=$list->fetch_array()){ $data[]=$row; } echo json_encode($data); }
原文地址:https://www.cnblogs.com/mengor/p/8275856.html
时间: 2024-10-07 20:00:18