初学ajax之省市联动demo.
city.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>省市联动</title>
<script type="text/javascript" src="js/city/city.js"></script>
</head>
<body>
<h3>ajax+java 省、市、区联动</h3>
<span style="color:red;">请选择你现居地:</span>
<select id="province" οnchange="loadCity();"></select>
<select id="city" οnchange="loadDistrict();"></select>
<select id="district"></select>
</body>
</html>
city.js:
window.onload = loadProvince; var ajaxObject; // 得到省 function loadProvince() { // 初始化 setSelect("province", "null", "请选择省:"); setSelect("city", "null", "请选择市:"); setSelect("district", "null", "请选择区:"); ajaxObject = getXMLHttpRequest(); if (ajaxObject) { var openURL = document.URL + "city"; var sendData = "type=getProvince"; ajaxObject.open("POST", openURL, true); ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajaxObject.onreadystatechange = loadProvinceStatechange; ajaxObject.send(sendData); } } // 得到省回调函数 function loadProvinceStatechange() { if (ajaxObject.readyState == 4) { if (ajaxObject.status == 200) { var jsonStr = ajaxObject.responseText; var jsonObj = eval("(" + jsonStr + ")"); for ( var i = 0; i < jsonObj.length - 1; i++) { var province = document.createElement("option"); province.value = jsonObj[i].serialId; province.innerHTML = jsonObj[i].provinceName; $("province").appendChild(province); } } } } // 得到市 function loadCity() { if ($("province").value != "null") { ajaxObject = getXMLHttpRequest(); if (ajaxObject) { var openURL = document.URL + "city"; var province = $("province").value; var sendData = "type=loadCity&province=" + province; ajaxObject.open("POST", openURL, true); ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajaxObject.onreadystatechange = loadCityStatechange; ajaxObject.send(sendData); } } else { setSelect("city", "null", "请选择市:"); setSelect("district", "null", "请选择区:"); } } // 得到市回调函数 function loadCityStatechange() { if (ajaxObject.readyState == 4) { if (ajaxObject.status == 200) { var jsonStr = ajaxObject.responseText; var jsonObj = eval("(" + jsonStr + ")"); setSelect("city", "null", "请选择市:"); for ( var i = 0; i < jsonObj.length - 1; i++) { var city = document.createElement("option"); city.value = jsonObj[i].serialId; city.innerHTML = jsonObj[i].cityName; $("city").appendChild(city); } } } } // 得到区 district function loadDistrict() { if ($("city").value != "null") { ajaxObject = getXMLHttpRequest(); if (ajaxObject) { var openURL = document.URL + "city"; var city = $("city").value; var sendData = "type=loadDistrict&city=" + city; ajaxObject.open("POST", openURL, true); ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajaxObject.onreadystatechange = loadDistrictStatechange; ajaxObject.send(sendData); } } else { setSelect("district", "null", "请选择区:"); } } // 得到区 callback function function loadDistrictStatechange() { if (ajaxObject.readyState == 4) { if (ajaxObject.status == 200) { var jsonStr = ajaxObject.responseText; var jsonObj = eval("(" + jsonStr + ")"); setSelect("district", "null", "请选择区:"); for ( var i = 0; i < jsonObj.length - 1; i++) { var district = document.createElement("option"); district.value = jsonObj[i].serialId; district.innerHTML = jsonObj[i].districtName; $("district").appendChild(district); } } } } // 得到 XMLHttpRequest对象 function getXMLHttpRequest() { var xmlHttp; try { xmlHttp = new XMLHttpRequest(); } catch (e) { try { xmlHttp = new ActiveXObject("microsoft.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { window.alert("对不起,你的浏览器不支持ajax!"); return false; } } } return xmlHttp; } // 初始化 select function setSelect(s_id, s_value, s_innerHTML) { $(s_id).length = 0; var ele = document.createElement("option"); ele.value = s_value; ele.innerHTML = s_innerHTML; $(s_id).appendChild(ele); } function $(id) { return document.getElementById(id); }
City.java:
package com.city;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class City extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String type = req.getParameter("type");
String sql;
String[] para;
if ("getProvince".equals(type)) {
// 得到省份
sql = "select serialId,provinceName from fch_province";
ArrayList<LinkedHashMap<String, Object>> provinces = (new SqlHelper())
.sqlQuery(sql, null);
String jsonProvinces = "";
for (int i = 0; i < provinces.size(); i++) {
HashMap<String, Object> hm = provinces.get(i);
Iterator<String> iterator = hm.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = hm.get(key).toString();
// 编写 json
if ("serialId".equals(key)) {
jsonProvinces += "{\"" + key + "\":\"" + value + "\",";
} else {
jsonProvinces += "\"" + key + "\":\"" + value + "\"},";
}
}
}
jsonProvinces = "[" + jsonProvinces + "{\"none\":\"none\"}]";
resp.getWriter().print(jsonProvinces);
// System.out.println(jsonProvinces);
} else if ("loadCity".equals(type)) {
// 得到城市
sql = "select serialId,cityName from fch_city where cityUpIdNum=?";
para = new String[] { req.getParameter("province") };
ArrayList<LinkedHashMap<String, Object>> cities = (new SqlHelper())
.sqlQuery(sql, para);
String jsonCities = "";
// 遍历
for (int i = 0; i < cities.size(); i++) {
HashMap<String, Object> hm = cities.get(i);
for (Entry<String, Object> city : hm.entrySet()) {
// json String
String key = city.getKey();
String value = city.getValue().toString();
if ("serialId".equals(key)) {
jsonCities += "{\"" + key + "\":\"" + value + "\",";
} else {
jsonCities += "\"" + key + "\":\"" + value + "\"},";
}
}
}
jsonCities = "[" + jsonCities + "{\"none\":\"none\"}]";
resp.getWriter().print(jsonCities);
// System.out.println(jsonCities);
} else if ("loadDistrict".equals(type)) {
// 根据省的districtUpIdNum得到 serialId,districtName
sql = "select serialId,districtName from fch_district where districtUpIdNum=?";
para = new String[] { req.getParameter("city") };
ArrayList<LinkedHashMap<String, Object>> districts = (new SqlHelper())
.sqlQuery(sql, para);
String jsonDistrict = "";
for (int i = 0; i < districts.size(); i++) {
HashMap<String, Object> hm = districts.get(i);
for (Entry<String, Object> district : hm.entrySet()) {
String key = district.getKey();
String value = district.getValue().toString();
if ("serialId".equals(key)) {
jsonDistrict += "{\"" + key + "\":\"" + value + "\",";
} else {
jsonDistrict += "\"" + key + "\":\"" + value + "\"},";
}
}
}
jsonDistrict = "[" + jsonDistrict + "{\"none\":\"none\"}]";
resp.getWriter().print(jsonDistrict);
// System.out.println(jsonDistrict);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
}
其他代码:详见源码..
效果图: