龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

php mysql+ajax的省市县三级联动

时间:2014-10-08 15:12来源:网络整理 作者:网络 点击:
分享到:
mysql+ajax的省市县三级联动 php开发中,想自己写一个mysql+ajax的省市县三级联动,一切都写好了,就等着返回xml或者json格式的数据了。查询是:$sql=quot;select * from cities where sid=1quot;;//1为江

php开发中,想自己写一个mysql+ajax的省市县三级联动,一切都写好了,就等着返回xml或者json格式的数据了。

查询是:$sql="select * from cities where sid=1";//1为江苏省的id.这个不用多说了

$res=mysql_query($sql);

在发一次包括数据库在内的代码以示感谢!!!
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://outofmemory.cn
精彩图集

赞助商链接