使用XMLHTTPRequest对象级联更新下拉框值
不使用dwr.ext.jquery等等些基于javascript脚本框架,而使用最原始XMLHTTPRequest对象级联更新下拉框值,中间需借助XML进行做为中间语言下面以 省 市 间级联更新作为示例:
后台以action连接数据库取数据
InitAction.java
//调用dao连接数据库//将取得数据放入request内request.setAttribute("listCity", listCity);//跳转到xmlCity.jsprequest.getRequestDispatcher("/xmlCity.jsp").forward(request,response);return null;
xmlCity.jsp
<%@ page language="java" import="java.util.*,com.etwin.persist.entity.*" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><?xml version="1.0" encoding="UTF-8"?><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><data><c:forEach items="${listCity}" var="city"> <row> <cityId>${city.cityId}</cityId> <cityName>${city.cityName}</cityName> </row> </c:forEach> </data>
显示页面代码
<script type="text/javascript"><!--var xmlhttp;function createXMLHTTPRequest(){if(window.ActiveXObject){xmlhttp =new ActiveXObject("Microsoft.XMLHttp");}else if(window.XMLHTTPRequest){ xmlhttp = new XMLHTTPRequest();}elsealert("加载信息失败,请尝试重新开启浏览器...");}function retrieveCity(){ //初始化url,将请求发送给action. var url = 'init.do?method=InitCity&proId='+document.getElementById("province").value; createXMLHTTPRequest(); xmlhttp.onreadystatechange = handleStateChange; xmlhttp.open( "GET", url, true );xmlhttp.send( null ); }function handleStateChange(){if( xmlhttp.readyState == 4&&xmlhttp.status == 200) { var city = document.getElementById( 'city' );//得到市下拉列表框控件 if(city!=null){ //清空原有下拉列表 city.options.length=0; n = xmlhttp.responseXML.getElementsByTagName("row"); l = n.length; //循环添加列表子项 for(var i=0;i<l;i++){ city.options.add(new Option(n.getElementsByTagName("cityName").firstChild.nodeValue, n.getElementsByTagName("cityId").firstChild.nodeValue)); } } }}//--></script>//需要更新的市下拉框<Select id=city size=1 name=city></Select>
在 省 下拉框onchange事件中调用retrieveCity函数即可(省下拉框在页面加载的时候就已经设置完毕).
最主要是得使用XML,用JS来解析XML然后设置下拉框值
页:
[1]