Controller
@Controller
@RequestMapping("json")
public class LinkageJSONController {
/**
[
{id:1,name="湖南"},
{id:2,name="广东"},
{id:3,name="湖北"}
]
*/
//获取省份
@RequestMapping("province")
public void getProvince(HttpServletResponse response) throws Exception {
response.setContentType("text/json;charset=utf-8");
//获取到所有的省份
StringBuilder sb = new StringBuilder(100);
sb.append("[");
List<Province> list = Province.getAllProvince();
for (Province province : list) {
sb.append("{id:").append(province.getId()).append(",name:\"").append(province.getName())
.append("\"},");
}
sb.deleteCharAt(sb.length()-1);
sb.append("]");
response.getWriter().write(sb.toString());
}
//获取城市
@RequestMapping("city")
public void getCity(Long pId, HttpServletResponse response) throws Exception {
response.setContentType("text/json;charset=utf-8");
//获取到所有的省份
StringBuilder sb = new StringBuilder(100);
sb.append("[");
List<City> list = City.getCityByProvinceId(pId);
for (City obj : list) {
sb.append("{id:").append(obj.getId()).append(",name:\"").append(obj.getName())
.append("\"},");
}
sb.deleteCharAt(sb.length()-1);
sb.append("]");
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","/json3/province.do",true);
//监听
var opHTML = "";
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var datas = eval("(" + ajax.responseText + ")");
for(var i = 0;i<datas.length;i++){
opHTML = opHTML + "<option value='" +datas[i].id + "'>" +datas[i].name+"</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","/json3/city.do?pId="+province.value,true);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var datas = eval("(" + ajax.responseText + ")");
for(var i = 0;i<datas.length;i++){
opHTML += "<option value='" +datas[i].id + "'>" +datas[i].name+"</option>";
}
city.innerHTML = opHTML;
}
};
ajax.send();
};
};