日期:2014-05-16  浏览次数:20594 次

Ajax动态更新下拉列表
    动态更新下拉列表是交互性Web应用的必备功能,可以为用户使用带去很大方便,希望以下示例能给学习Ajax的朋友们一些启示。

JSP页面:select-tag.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'select-tag.jsp' starting page</title>
   
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

  </head>
  <script type="text/javascript">
  var xmlHttp;
 
  function createXMLHttpRequest(){
  if(window.ActiveXObject){
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  else if(window.XMLHttpRequest){
  xmlHttp=new XMLHttpRequest();
  }
  }
 
  function updateSelect(){
  var selected=document.all.slt1.value;
  createXMLHttpRequest();
  xmlHttp.onreadystatechange=processor;
  xmlHttp.open("GET","CreateXML?selected="+selected);
  xmlHttp.send(null);
  }
 
  function processor(){
  var result;
  if(xmlHttp.readyState==4){
  if(xmlHttp.status==200){
  result=xmlHttp.responseXML.getElementsByTagName("city");
  while(document.all.slt2.options.length>0){
  document.all.slt2.removeChild(document.all.slt2.childNodes[0]);
  }
 
  for(var i=0;i<result.length;i++){
  var option=document.createElement("OPTION");
  option.text=result[i].childNodes[0].childNodes[0].nodeValue;
  option.value=result[i].childNodes[1].childNodes[0].nodeValue;
  document.all.slt2.options.add(option);
  }
  }
  }
  }
  </script>
  <body>
    This is my JSP page. <br>
    <p>请选择省份:
    <select id="slt1" onChange="updateSelect()">
    <option value="1">陕西</option>
    <option value="2">湖南</option>
    </select>
    城市:
    <select id="slt2">
    <option>请选择城市</option>
    </select>
  </body>
</html>


配置文件:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>CreateXML</servlet-name>
    <servlet-c