<html"> <head> <Meta content="text/html; charset=gb2312" /> <title>ajax应用实例</title> <script> var xmlhttp=null; function GetXmlHttpRequest() { var xmlhttp=null; try{ xmlhttp = new XMLHttpRequest(); } catch (e){ try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ xmlhttp = new ActiveXObject("Microsft.XMLHTTP"); } catch (e){ xmlhttp = false; } } } return xmlhttp; } function sendRequest(){ var tt=document.getElementById("province").value; xmlhttp = GetXmlHttpRequest(); if(xmlhttp == null){ alert("浏览器不支持"); return; } var url = "b.PHP"; url+="?prov=" + tt; xmlhttp.open("GET",url,true); xmlhttp.onreadystatechange = updatePage; xmlhttp.send(null); } function updatePage(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ var response = xmlhttp.responseText; document.getElementById("city").innerHTML = response; } } </script> </head> <body> <h3>请选择一个省份</h3> <form id="form" name="form" action="b.PHP"> <div> <select id="province" name="province" onchange="sendRequest()"> <option value="">请选择一个省份(自治区)</option> <option value="ah"> 安徽</option> <option value="fj">福建</option> <option value="gs"> 甘肃</option> </select> </div> </form> <div id="city"> </div> </body> </html>
<?PHP $str = $_GET['prov']; $city_Arr = array( "ah" =>"合肥", "fj"=>"福州", "gs"=>"兰州" ); if(empty($_GET['prov'])){ echo "您未选择省份。。。"; } else{ $prov = $_GET['prov']; $city =$city_Arr[$prov]; echo iconv("GB2312","UTF-8",'您所选择的省份的省会为:'.$city); } ?>
4、重点说明:
正确的:
xmlhttp.onreadystatechange = updatePage;
错误的:
xmlhttp.onreadystatechange = updatePage();
如果加了()则只能调用一次updatePage。