首先要把html文件写好,<select id="provinceID" style="width:120px"> <option>选择省份</option> <option>湖南省</option> <option>广东省</option> </select> <select id="cityID"> <option>选择城市</option> </select>还需要我们把之前写的那个createAJAX()引入进来。
<script type="text/javascript" src="js/ajax.js"></script>
然后就继续在这个script脚本中进行编写了。
//定位省份下拉框,同时添加内容改变事件
document.getElementById("provinceID").onchange=function(){
//清空
var cityElement=document.getElementById("cityID");
cityElement.options.length=1; //只保留第一个
//获取选中省份的名字
var index=this.selectedIndex;
var optionElement=this[index];
//获取选中的option标签中的内容
var province=optionElement.innerHTML;
if("选择省份"!=province){
var ajax=createAJAX();
var method="POST";
var url="${pageContext.request.contextPath}/servlet/Province?time="+new Date().getTime();
ajax.open(method,url);
//设置ajax请求头为post,它会将请求体重的汉子自动进行utf-8的编码
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
var content="province="+province;
ajax.send(content);
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
var xmlDocument=ajax.responseXML;
//按照dom去解析xml文档
var cityElementArray=xmlDocument.getElementsByTagName("city");
var size=cityElementArray.length;
for(var i=0;i<size;i++){
//innerHTML只能在html/jsp中使用,不能再xml中使用
var city=cityElementArray[i].firstChild.nodeValue;
var optionElement=document.createElement("option");
optionElement.innerHTML=city;
cityElement.appendChild(optionElement);
}
}
}
}
}
}
对于服务端,采用的是post方法:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String province=request.getParameter("province");
//xml格式的数据
response.setContentType("text/xml;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write("<?xml version='1.0' encoding='UTF-8' ?>");
pw.write("<root>");
if("广东省".equals(province)){
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>");
pw.flush();
pw.close();
}
效果如下:
源码地址:https://github.com/sdksdk0/AJAX-Demo