基于ajax二级联动

前端之家收集整理的这篇文章主要介绍了基于ajax二级联动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

<body>
<select id="provinceID">
<option> 选择省份</option>
<option> 广东</option>
<option> 湖南</option>
<option> 江苏</option>

</select>
<hr/>

<select id="cityID" style="width: 90px">
<option> 选择城市</option>

</select>
<script type="text/javascript">
document.getElementById("provinceID").onchange=function(){
var citySelectElement=document.getElementById("cityID");
var size=citySelectElement.options.length;
if(size>1){
for(var i=size-1;i>0;i--)
{
citySelectElement.removeChild(citySelectElement.options[i]);
}

}

var optionElement=this[this.selectedIndex];
var province=optionElement.firstChild.nodeValue;

//创建引擎
var xhr=createAJAX();
var method="POST";
var url="${pageContext.request.contextPath}/ProvinceCityXMLServlet?time="+new Date().getTime();
xhr.open(method,url);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
var content="province="+province;

xhr.send(content);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
var xmlDocument=xhr.responseXML;

//解析xml文档
var cityElementArray=xmlDocument.getElementsByTagName("city");
var size=cityElementArray.length;
for(var i=0;i<size;i++){
var cityElement=cityElementArray[i];
var city=cityElement.firstChild.nodeValue;

var optionElement=document.createElement("option");

optionElement.innerHTML=city;

var citySelectElement=document.getElementById("cityID");
citySelectElement.appendChild(optionElement);

}
}
}
}
}



function createAJAX(){
var xhr = null;
try{
xhr = new ActiveXObject("microsoft.xmlhttp");
}catch(e1){
try{
xhr = new XMLHttpRequest();
}catch(e2){
//alert("更换浏览器");
}
}
return xhr;
}

</script>
</body>

servlet部分:

request.setCharacterEncoding("utf-8"); String province=request.getParameter("province"); response.setContentType("text/xml;charset=utf-8"); PrintWriter pw=response.getWriter(); pw.write("<root>"); if("广东".equals(province)){ pw.write("<city>广州</city>"); pw.write("<city>佛山</city>"); pw.write("<city>中山</city>"); pw.write("<city>深圳</city>"); pw.write("<city>珠海</city>"); } else if("湖南".equals(province)){ pw.write("<city>张家界</city>"); pw.write("<city>株洲</city>"); pw.write("<city>湘潭</city>"); pw.write("<city>长沙</city>"); } else if("江苏".equals(province)){ pw.write("<city>南京</city>"); pw.write("<city>苏州</city>"); pw.write("<city>无锡</city>"); pw.write("<city>海门</city>"); } pw.write("</root>"); }

猜你在找的Ajax相关文章