二級聯動JavaScript+JSP
erji2.jsp 文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page import="cc.apl330.Citys_Arr"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'erji2.jsp' starting page</title> </head> <!-- init()用于初始化聯動選項 --> <body onload="init()"> <% //讀取數據 Citys_Arr ca = null ; %> <form action="" name="fom"> <select name="s1" onchange="sel()"> <% ca = new Citys_Arr() ; for(int i = 0 ; i < ca.getCitys().length; i++ ) { %> <option><%=ca.getCitys()[i]%></option> <% } %> </select> <select name="s2"> </select> </form> </body> <script type="text/javascript"> <% int citys = ca.getCitys().length ; %> var select2 = new Array(<%=citys%>) ; <!-- //初始化 --> function init() { <% for(int i = 0 ; i < citys ; i++ ) { %> select2[<%=i%>] = new Array() ; <% } %> <% for(int x = 0 ; x < citys ;x++){ for(int y = 0 ; y < ca.getZone()[u].length ; y++){ %> select2[<%=x%>][<%=y%>] = new Option("<%=ca.getZone()[x][y]%>" , "<%=ca.getZone()[x][y]%>"); <% } } %> } <!-- //根據前一項選擇加載聯動數據 --> function sel() { var pp = document.fom.s1.options.selectedIndex ; var temp = document.fom.s2; for (i = 0; i < select2[pp].length; i++) { temp.options[i] = new Option(select2[pp][i].text, select2[pp][i].value); } temp.options[0].selected = true; } </script> </html>
Citys_Arr.java //用于讀取數據
package cc.apl330; public class Citys_Arr { private String[] citys = {"桂林","崇左"} ; private String[][] zone = { {"平樂","臨桂","荔浦","二塘"}, {"龍州","天等","花山","樂一"} } ; public String[] getCitys() { return citys; } public void setCitys(String[] citys) { this.citys = citys; } public String[][] getZone() { return zone; } public void setZone(String[][] zone) { this.zone = zone; } }