DIV CSS 佈局教程網

Ajax 實現省市區三級聯動下拉選單(資料來自 MySQL)
編輯:AJAX基礎知識     

地址選擇是表單裡最經典的連動場景:選了省要列出所轄市,選了市要列出所轄區。實作要點在於「三層資料各自獨立請求、上一層變動時清空並重載下一層」。以下用原生 XMLHttpRequest + Servlet + MySQL 完整示範。

一、前端頁面 address.html

<!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>

二、Servlet:依 method 分流

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());
    }
}

三、DAO 介面

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);
}

四、DAO 實作

三個查詢結構幾乎一致,只有表名與 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 + "]";
    }
}

這份程式碼可以更好的地方

  • SQL 拼接有注入風險:"... where fatherID = " + provinceId 應改成 PreparedStatement 佔位符。雖然這裡已用 Integer.parseInt() 轉型,算是有一道防線,但養成參數化查詢的習慣更重要。
  • 用 new Function() 解析 JSON 不安全:應改用 JSON.parse(responseContents)。前者會執行字串內容,若回應被污染就是 XSS 入口。
  • innerHTML 累加 option 較耗效能:資料量大時改用 new Option(text, value) 後 add(),或直接組 DOM,並以 replaceChildren() 清空。
  • 請求方式用 GET 即可:這類只讀查詢沒必要用 POST,GET 也能被瀏覽器快取,減少資料庫壓力。
  • 清空要確實:上一層變動時務必把下兩層重設為初始 option,否則會出現「用 A 省的市配 B 省的區」這種髒資料。
  • 三級以上可考慮一次撈回:若資料量不大(例如整份行政區約幾千筆),一次載入並在前端篩選,反而比每層都發請求更快,也沒有連線延遲的問題。

以上就是省市區三級聯動的完整實作,希望對你的學習有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved