Controller
@Controller
@RequestMapping("xml")
public class LinkageXMLController {
/**
<datas>
<data id="1">湖南</data>
<data id="2">广东</data>
<data id="3">湖北</data>
</datas>
*/
//获取省份
@RequestMapping("province")
public void getProvince(HttpServletResponse response) throws Exception {
response.setContentType("text/xml;charset=utf-8");
//获取到所有的省份
StringBuilder sb = new StringBuilder(100);
sb.append("<datas>");
List<Province> list = Province.getAllProvince();
for (Province obj : list) {
sb.append("<data id='").append(obj.getId()).append("'>").append(obj.getName())
.append("</data>");
}
sb.append("</datas>");
response.getWriter().write(sb.toString());
}
//获取城市
@RequestMapping("city")
public void getCity(Long pId, HttpServletResponse response) throws Exception {
response.setContentType("text/xml;charset=utf-8");
//获取到所有的省份
StringBuilder sb = new StringBuilder(100);
sb.append("<datas>");
List<City> list = City.getCityByProvinceId(pId);
for (City obj : list) {
sb.append("<data id='").append(obj.getId()).append("'>").append(obj.getName())
.append("</data>");
}
sb.append("</datas>");
response.getWriter().write(sb.toString());
}
}
HTML
<body>
<select id="provinces">
<option value="-1">--请选择--</option>
</select>
<select id="cities">
<option value="-1">--请选择--</option>
</select>
</body>
JS
window.onload = function() {
//获取到省份的选择器
var province = document.getElementById("provinces");
console.log(province);
//发送省份的请求
//创建ajax对象
var ajax = new XMLHttpRequest();
//open
ajax.open("get","/xml/province.do",true);
//监听
var opHTML = "";
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var doc = ajax.responseXML;
var datas = doc.getElementsByTagName("data");
for(var i = 0;i<datas.length;i++){
opHTML = opHTML + "<option value='" +datas[i].id + "'>" +datas[i].innerHTML+"</option>";
}
province.innerHTML += opHTML;
}
};
ajax.send();
province.onchange = function() {
var city = document.getElementById("cities");
var opHTML = "<option value='-1'>--请选择--</option>";
//优化,如果省选的是请选择,就没必要发送请求了
if (province.value < 0) {
city.innerHTML = opHTML;
return;
}
ajax.open("get","/xml/city.do?pId="+province.value,true);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var datas = ajax.responseXML;
var ps = datas.getElementsByTagName("data");
for(var i = 0;i<ps.length;i++){
opHTML += "<option value='" +ps[i].id + "'>" +ps[i].innerHTML+"</option>";
}
city.innerHTML = opHTML;
}
};
ajax.send();
};
};