ajax实现省市联动(version 1)

来源:互联网 发布:淘宝搜索词查询在哪里 编辑:程序博客网 时间:2024/05/21 16:30

    需要写出联动程序,ajax最合适,毫不熟悉,看了视频然后自己调了下,一个简单的省市联动版本1。

    主界面showCities.php

<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"/><script type = "text/javascript">function getXmlHttpObject(){var xmlHttpRequest;if(window.ActiveXObject){xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");}else{xmlHttpRequest = new XMLHttpRequest();}return xmlHttpRequest;}var myXmlHttpRequest = "";function getCities(){myXmlHttpRequest = getXmlHttpObject();if(myXmlHttpRequest){ var url = "http://localhost/apt/aqxxgl/ajax/showCitiesPro.php";//postvar data = "province=" + $('sheng').value;myXmlHttpRequest.open("post",url,true);myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");myXmlHttpRequest.onreadystatechange=chuli;myXmlHttpRequest.send(data);}}function chuli(){if(myXmlHttpRequest.readyState==4){if(myXmlHttpRequest.status==200){//alert(myXmlHttpRequest.responseXML);var cities = myXmlHttpRequest.responseXML.getElementsByTagName("city");//window.alert(cities.length);$('city').length = 0;var myOption = document.createElement("option");myOption.innerText = "--城市--";$('city').appendChild(myOption);for(var i=0;i<cities.length;i++){var city_name = cities[i].childNodes[0].nodeValue;//window.alert(city_name);var myOption = document.createElement("option");myOption.value = city_name;myOption.innerText = city_name;$('city').appendChild(myOption);}//取出服务器的数据/*var cities = myXmlHttpRequest.responseXML.getElementsByTagName("city");//遍历并取出城市$('city').length = 0;for(var i=0;i<cities.length;i++){var city_name = cities[i].childNodes[0].nodeValue;//创建新的元素optionvar myOption = document.createElement("option");myOption.value=city_name;myOption.innerHTML = city_name;//添加到select框中$('city').appendChild(myOption);}*///window.alert(myXmlHttpRequest.responseXML);}else {alert("error!~");}}}function $(id){return document.getElementById(id);}</script></head><body><select id = "sheng" onchange="getCities();"><option value = "">---省---</option><option value = "zhejiang">浙江</option><option value = "jiangsu">江苏</option></select><select id = "city"><option value = "">--城市--</option></select><select id = "county"><option value = "">--县城--</option></select></body></html>
     调动的showCitiesPro.php。
<?php header("Content-Type:text/xml;charset=utf-8");header("Cache-Control:no-cache");$province = $_POST['province'];file_put_contents("d:/mylog.log",$province."\r\n",FILE_APPEND);//到数据库查询省有哪些(现在先不到数据库)if($province=="zhejiang"){$info = "<province><city>杭州</city><city>温州</city><city>宁波</city></province>";}else if($province=="jiangsu"){    $info = "<province><city>南京</city><city>徐州</city><city>苏州</city></province>";}echo $info;//echo "data received:";?>
    这样可以实现简单的二级联动,后续更深入待续。
0 0
原创粉丝点击