- 在发一次包括数据库在内的代码以示感谢!!!
- php页面:
- <?php
- //这里两句话很重要,第一讲话告诉浏览器返回的数据是xml格式
- header("Content-Type: text/html;charset=utf-8");
- //告诉浏览器不要缓存数据
- header("Cache-Control: no-cache");
- $conn=mysql_connect("localhost","root","123");
- mysql_select_db("ajax");
- mysql_query("set names utf8");
- if(isset($_POST['sid'])){
- $sid=$_POST['sid'];
- //file_put_contents("D:/a.txt",$sid);
- $sql_shi="select shi from shi where sid=$sid";
- $res_shi=mysql_query($sql_shi);
- $arr="";
- while($row=mysql_fetch_array($res_shi)){
- $arr[]=$row;
- }
- $a=json_encode($arr);
- echo '{"aa":'.$a.'}';
- }
- ?>
- js页面:
- <script type="text/javascript">
- //创建xmlHttpRequest对象
- function GetXmlHttpObject()
- {
- var xmlHttp=null;
- try
- {
- // Firefox, Opera 8.0+, Safari
- xmlHttp=new XMLHttpRequest();
- }
- catch (e)
- {
- // Internet Explorer
- try
- {
- xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
- }
- catch (e)
- {
- xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
- }
- }
- return xmlHttp;
- }
- var xhr="";
- function checkCity(){
- xhr=GetXmlHttpObject();
- if(xhr){
- var url="/ajax/citiesProcess.php";
- var data="sid="+$("sheng").value;
- xhr.open("post",url,true);
- xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
- xhr.onreadystatechange=chuli;
- xhr.send(data);
- }
- }
- function $(id){
- return document.getElementById(id);
- }
- function chuli(){
- if(xhr.readyState==4 && xhr.status==200){
- var result=xhr.responseText;
- //window.alert(result);
- var message=eval("("+result+")");
- $("city").length=0;
- myoption=document.createElement("option");
- myoption.innerText="--市--";
- $("city").appendChild(myoption);
- for(var i=0;i<message.aa.length;i++){
- var shi_name=message.aa[i].shi;
- myoption=document.createElement("option");
- myoption.value=shi_name;
- myoption.innerText=shi_name;
- $("city").appendChild(myoption);
- }
- //window.alert(message.aa[].length);
- }
- }
- </script>
- html页面:
- <body>
- <select id="sheng" onchange="checkCity();">
- <option value="">---省---</option>
- </select>
- <select id="city" onchange="chkxian();">
- <option value="">--市--</option>
- </select>
- <select id="county">
- <option value="">--县--</option>
- </select>
- </body>
- //该片段来自于http://www.codesnippet.cn/detail/050920135661.html
来源: http://www.codesnippet.cn/detail/050920135661.html