无论如何,正如我所说,我终于设法自己做到了,所以这是我的答案......
我像这样从我的控制器收到地图(我正在使用 Spring,不知道这如何与其他框架一起使用):
<c:set var="manufacturersAndModels" scope="page" value="${MANUFACTURERS_AND_MODELS_MAP}"/>
这些是我的组合:
<select id="manufacturersList" name="manufacturersList" onchange="populateModelsCombo(this.options[this.selectedIndex].index);" >
<c:forEach var="manufacturersItem" items="<%= manufacturers%>">
<option value='<c:out value="${manufacturersItem}" />'><c:out value="${manufacturersItem}" /></option>
</c:forEach>
</select>
select id="modelsList" name="modelsList"
<c:forEach var="model" items="<%= models %>" >
<option value='<c:out value="${model}" />'><c:out value="${model}" /></option>
</c:forEach>
</select>
我导入了以下类(当然,有些名称已更改):
<%@ page import="org.mycompany.Car,java.util.Map,java.util.TreeMap,java.util.List,java.util.ArrayList,java.util.Set,java.util.Iterator;" %>
这是完成所有艰苦工作的代码:
<script type="text/javascript">
<%
Map mansAndModels = new TreeMap();
mansAndModels = (TreeMap) pageContext.getAttribute("manufacturersAndModels");
Set manufacturers = mansAndModels.keySet(); //We'll use this one to populate the first combo
Object[] manufacturersArray = manufacturers.toArray();
List cars;
List models = new ArrayList(); //We'll populate the second combo the first time the page is displayed with this list
//initial second combo population
cars = (List) mansAndModels.get(manufacturersArray[0]);
for(Iterator iter = cars.iterator(); iter.hasNext();) {
Car car = (Car) iter.next();
models.add(car.getModel());
}
%>
function populateModelsCombo(key) {
var modelsArray = new Array();
//Here goes the tricky part, we populate a two-dimensional javascript array with values from the map
<%
for(int i = 0; i < manufacturersArray.length; i++) {
cars = (List) mansAndModels.get(manufacturersArray[i]);
Iterator carsIterator = cars.iterator();
%>
singleManufacturerModelsArray = new Array();
<%
for(int j = 0; carsIterator.hasNext(); j++) {
Car car = (Car) carsIterator.next();
%>
singleManufacturerModelsArray[<%= j%>] = "<%= car.getModel()%>";
<%
}
%>
modelsArray[<%= i%>] = singleManufacturerModelsArray;
<%
}
%>
var modelsList = document.getElementById("modelsList");
//Empty the second combo
while(modelsList.hasChildNodes()) {
modelsList.removeChild(modelsList.childNodes[0]);
}
//Populate the second combo with new values
for (i = 0; i < modelsArray[key].length; i++) {
modelsList.options[i] = new Option(modelsArray[key][i], modelsArray[key][i]);
}
}