上网找了下资料,参考着做了个
JSP页面,使用JSTL的标签。
- <tr>
- <td width="10%">所属栏目</td>
- <td width="90%"><select name="columnInfo" id="columnInfo">
- <option value="0">--请选择--</option>
- <c:forEach var="columns" items="${columnsList}">
- <option value="${columns.id}">${columns.name}</option>
- </c:forEach>
- </select><select name="subColumnInfo" id="subColumnInfo"></select></td>
- </tr>
JS
- $(function(){
- $("#columnInfo").change(function(){
- $.getJSON("NewsAction!ajax",{parColumnId:$(this).val()},function(myJSON){
- var myOptions="";
- for(var i=0;i<myJSON.length;i++){
- myOptions += '<option value="' + myJSON[i].optionValue + '">' +
- myJSON[i].optionDisplay + '</option>';
- }
- $("#subColumnInfo").empty();
- $("#subColumnInfo").html(myOptions);
- });
- });
- $("#columnInfo").change();
- })
后台处理
- // 处理AJAX级联请求
- public void ajax() throws Exception {
- String JSON_text = "";
- if (parColumnId == 0) {
- JSON_text = "[{optionValue:'0',optionDisplay:'--请选择--'}]";
- } else {
- List<Columns> subColumnList = columnService
- .findColumns(parColumnId);
- if (subColumnList.size() > 0) {
- JSON_text = "[";
- for (int i = 0; i < subColumnList.size(); i++) {
- Columns sub = subColumnList.get(i);
- JSON_text += "{optionValue:'" + sub.getId()
- + "',optionDisplay:'" + sub.getName() + "'}";
- if (i < subColumnList.size() - 1) {
- JSON_text += ", ";
- } else if (i == subColumnList.size() - 1) {
- JSON_text += "]";
- }
- }
- }
- }
- PrintWriter out = null;
- try {
- ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
- out = ServletActionContext.getResponse().getWriter();
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- out.write(JSON_text);
- out.close();
- }