本例實現省、市二級聯動:選擇某省時,該省下屬的市會在另一個下拉框中顯示。Ajax 通過解析後端返回的 XML 數據完成填充,省市數據均來自數據庫。
<script type="text/javascript">
var xmlHttp = null;
// 創建對象
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "GetProvince?time=" + new Date().getTime();
function getsheng(){
xmlHttp.open("post", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send();
xmlHttp.onreadystatechange = getprovince;
}
function getprovince(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var xmlFile = xmlHttp.responseXML;
var province = xmlFile.getElementsByTagName("province");
var pselect = document.getElementById("sheng");
for(var i = 0; i < province.length; i++){
var shorter = province[i].getAttribute("name");
var provincename = province[i].text;
pselect.options.add(new Option(provincename, shorter)); // (text, value)
}
}
}
function getcity(){
xmlHttp.open("post", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var province = document.getElementById("sheng").value;
xmlHttp.send("province=" + province);
xmlHttp.onreadystatechange = setcity;
}
function setcity(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var city = document.getElementById("city");
city.options.length = 0;
var citys = xmlHttp.responseXML.getElementsByTagName("city");
for(var i = 0; i < citys.length; i++){
city.options.add(new Option(citys[i].text, citys[i].text));
}
}
}
</script>
<body onload="getsheng()">
省:<select id="sheng" onchange="getcity()"><option>請選擇</option></select>
市:<select id="city"></select>
</body>
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String province = request.getParameter("province");
if(province != null){
sendCity(request, response, province);
}else{
ShengDao sd = new ShengDao();
List<Sheng> list = sd.selAll();
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
out.println("<?xml version='1.0' encoding='UTF-8'?>");
out.println("<china>");
for (Sheng sheng : list) {
out.print("<province name='" + sheng.getShorter() + "'>"
+ sheng.getProvince() + "</province>");
}
out.println("</china>");
}
}
public void sendCity(HttpServletRequest request, HttpServletResponse response, String shorter){
try {
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
ShengDao sd = new ShengDao();
List<City> list = sd.selAll(shorter);
out.println("<?xml version='1.0' encoding='UTF-8'?>");
out.println("<province>");
for (City city : list) {
out.println("<city name='" + city.getShorter() + "'>"
+ city.getCityname() + "</city>");
}
out.println("</province>");
} catch (IOException e) {
e.printStackTrace();
}
}
前端頁面加載時先取全省列表填充第一個下拉框;選擇某省後把省代碼提交後端,後端返回對應市的 XML,前端解析 responseXML 並動態填充第二個下拉框,實現二級聯動。