地址選擇是表單裡最經典的連動場景:選了省要列出所轄市,選了市要列出所轄區。實作要點在於「三層資料各自獨立請求、上一層變動時清空並重載下一層」。以下用原生 XMLHttpRequest + Servlet + MySQL 完整示範。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>省市區三級聯動</title>
</head>
<script type="text/javascript">
/** 取得 XMLHttpRequest 物件(含舊 IE 相容) */
function getajaxHttp() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest(); // Firefox / Opera / Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // IE
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的瀏覽器不支持 AJAX!");
return false;
}
}
}
return xmlHttp;
}
/**
* 發送 ajax 請求
* @param url 請求位址
* @param methodtype post / get
* @param con true(非同步) | false(同步)
* @param functionName 成功後的回呼函式,接收 responseText
*/
function ajaxrequest(url, methodtype, con, functionName) {
var xmlhttp = getajaxHttp();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
functionName(xmlhttp.responseText);
}
};
xmlhttp.open(methodtype, url, con);
xmlhttp.send();
}
// 頁面載入後先抓省
window.onload = function () {
ajaxrequest("addressSerlvet?method=provincial", "POST", true, addrResponse);
};
// 動態填入省
function addrResponse(responseContents) {
var jsonObj = new Function("return " + responseContents)();
for (var i = 0; i < jsonObj.addrList.length; i++) {
document.getElementById('select').innerHTML +=
"<option value='" + jsonObj.addrList[i].id + "'>"
+ jsonObj.addrList[i].address + "</option>";
}
}
// 選省之後
function pChange() {
// 先清空市與區,避免殘留上一筆資料
document.getElementById('selectCity').innerHTML = "<option value='-1'>請選擇市</option>";
document.getElementById('selectArea').innerHTML = "<option value='-1'>請選擇區</option>";
document.getElementById("addr").innerHTML = "";
var val = document.getElementById('select').value;
if (val == -1) {
document.getElementById('selectCity')[0].selected = true;
return;
}
ajaxrequest("addressSerlvet?method=city&provincial=" + val, "POST", true, cityResponse);
}
function cityResponse(responseContents) {
var jsonObj = new Function("return " + responseContents)();
for (var i = 0; i < jsonObj.cityList.length; i++) {
document.getElementById('selectCity').innerHTML +=
"<option value='" + jsonObj.cityList[i].id + "'>"
+ jsonObj.cityList[i].address + "</option>";
}
}
// 選市之後
function cChange() {
var val = document.getElementById('selectCity').value;
ajaxrequest("addressSerlvet?method=area&cityId=" + val, "POST", true, areaResponse);
}
function areaResponse(responseContents) {
var jsonObj = new Function("return " + responseContents)();
for (var i = 0; i < jsonObj.areaList.length; i++) {
document.getElementById('selectArea').innerHTML +=
"<option value='" + jsonObj.areaList[i].id + "'>"
+ jsonObj.areaList[i].address + "</option>";
}
}
// 點擊確定
function confirM() {
var p = document.getElementById("select");
var pTex = p.options[p.options.selectedIndex].text;
if (p.value == -1) { alert("請選擇省"); return; }
var city = document.getElementById("selectCity");
var cityTex = city.options[city.options.selectedIndex].text;
if (city.value == -1) { alert("請選擇市"); return; }
var area = document.getElementById("selectArea");
var areaTex = area.options[area.options.selectedIndex].text;
if (area.value == -1) { alert("請選擇區"); return; }
var addr = document.getElementById("addr").value;
document.getElementById("show").innerHTML =
"您選擇的地址為 " + pTex + " " + cityTex + " " + areaTex + " " + addr;
}
</script>
<body>
<select id="select" onchange="pChange()">
<option value="-1">請選擇省</option>
</select>
<select id="selectCity" onchange="cChange()">
<option value='-1'>請選擇市</option>
</select>
<select id="selectArea">
<option value='-1'>請選擇區</option>
</select>
<input type="text" id="addr" />
<button onclick="confirM();">確定</button>
<div id="show"</div>
</body>
</html>
package cn.bestchance.servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import cn.bestchance.dao.AddressDao;
import cn.bestchance.dao.impl.AddressDaoImpl;
import cn.bestchance.entity.Address;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@WebServlet("/addressSerlvet")
public class AddressSerlvet extends HttpServlet {
private static final long serialVersionUID = 1L;
private AddressDao dao = new AddressDaoImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String method = request.getParameter("method");
if ("provincial".equals(method)) getProvincial(request, response);
if ("city".equals(method)) getCity(request, response);
if ("area".equals(method)) getArea(request, response);
}
/** 取得全部省 */
protected void getProvincial(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ArrayList<Address> addrList = dao.getProvince();
JSONObject jsonObj = new JSONObject();
jsonObj.put("addrList", JSONArray.fromObject(addrList));
response.getWriter().print(jsonObj.toString());
}
/** 依省 id 取得市 */
protected void getCity(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String provinceId = request.getParameter("provincial");
ArrayList<Address> addrList = dao.getCityByProvinceId(Integer.parseInt(provinceId));
JSONObject jsonObj = new JSONObject();
jsonObj.put("cityList", JSONArray.fromObject(addrList));
response.getWriter().print(jsonObj.toString());
}
/** 依市 id 取得區 */
protected void getArea(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String cityId = request.getParameter("cityId");
ArrayList<Address> areaList = dao.getAreaByCityId(Integer.parseInt(cityId));
JSONObject jsonObj = new JSONObject();
jsonObj.put("areaList", JSONArray.fromObject(areaList));
response.getWriter().print(jsonObj.toString());
}
}
package cn.bestchance.dao;
import java.util.ArrayList;
import cn.bestchance.entity.Address;
public interface AddressDao {
/** 取得省的 id 和名稱 */
ArrayList<Address> getProvince();
/** 依省 id 取得市 */
ArrayList<Address> getCityByProvinceId(int provinceId);
/** 依市 id 取得區 */
ArrayList<Address> getAreaByCityId(int cityId);
}
三個查詢結構幾乎一致,只有表名與 fatherID 條件不同:
package cn.bestchance.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import cn.bestchance.dao.AddressDao;
import cn.bestchance.entity.Address;
import cn.bestchance.util.DBUtil;
public class AddressDaoImpl implements AddressDao {
private DBUtil db = new DBUtil();
@Override
public ArrayList<Address> getProvince() {
return query("select * from province");
}
@Override
public ArrayList<Address> getCityByProvinceId(int provinceId) {
return query("select * from city where fatherID = " + provinceId);
}
@Override
public ArrayList<Address> getAreaByCityId(int cityId) {
return query("select * from area where fatherID = " + cityId);
}
/** 共用查詢:省、市、區三張表欄位結構相同,可抽成一個方法 */
private ArrayList<Address> query(String sql) {
ArrayList<Address> addrList = new ArrayList<Address>();
db.openConnection();
ResultSet rs = db.excuteQuery(sql);
try {
while (rs.next()) {
Address addr = new Address();
addr.setId(rs.getInt(2));
addr.setAddress(rs.getString(3));
addrList.add(addr);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
}
db.closeResoure();
}
return addrList;
}
}
package cn.bestchance.entity;
public class Address {
private int id;
private String address;
public Address() { super(); }
public Address(int id, String address) {
super();
this.id = id;
this.address = address;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
@Override
public String toString() {
return "Address [id=" + id + ", address=" + address + "]";
}
}
"... where fatherID = " + provinceId 應改成 PreparedStatement 佔位符。雖然這裡已用 Integer.parseInt() 轉型,算是有一道防線,但養成參數化查詢的習慣更重要。new Function() 解析 JSON 不安全:應改用 JSON.parse(responseContents)。前者會執行字串內容,若回應被污染就是 XSS 入口。new Option(text, value) 後 add(),或直接組 DOM,並以 replaceChildren() 清空。以上就是省市區三級聯動的完整實作,希望對你的學習有所幫助。