1.实现思路:
在下拉列表框中编写js函数触发onchange事件,在这js函数中将选中的name值通过ajax传给后台servlet,在servlet中通过request.getParameter("name")获得选中的name,调用后台的方法得到相应的城市列表(此例没有数据库)。然后如果查到响应的城市的话将其列表组成一个用"#"号分割的字符串str,将其放到response的Writer中。然后在回调函数中接受应答字符串str,调用split("#")方法得到相应的城市数组,然后取得index.jsp的下拉列表框ID,将相应的城市用循环动态的加入到城市列表框中。
2.具体例子
(1)index.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%
- String path = request.getContextPath();
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>以城市与省份为例,用ajax实现二级联动</title>
- </head>
- <mce:script type="text/javascript"><!--
- function $(id){
- return document.getElementById(id);
- }
- var xmlHttp;
- //根据浏览器创建xmlHttpRequest对象
- function getXmlHttpRequest() {
- //针对FireFox,Mozillar,Opera,Safari,IE7,IE8
- if(window.XMLHttpRequest)
- return new XMLHttpRequest();
- //针对IE5,IE5.5,IE6
- else if (window.ActiveXObject){
- //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个JS数组中。
- var activexName = ["MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
- for(var i = 0; i<activexName.length; i++){
- //取出一个控件名进行创建,如果成功就终止循环
- try{
- return new ActiveXObject(activexName[i]);
- break;
- }catch(e){
- return null;
- }
- }
- }
- }
- function getCity(){
- xmlHttp=getXmlHttpRequest();
- var url="GetCity?provinceName="+$("provinceid").value;
- // 注册回调函数,只写函数名,不能写括号,写括号表示调用函数
- xmlHttp.onreadystatechange = getResult;
- // 确定发送请求的方式和URL以及是否同步执行下段代码
- xmlHttp.open("GET", url, true);
- //发送数据,开始和服务器进行交互
- xmlHttp.send(null);
- }
- //回调函数
- function getResult(){
- if (xmlHttp.readyState == 4) { // 判断对象状态
- if (xmlHttp.status == 200) { // 信息已经成功返回,开始处理信息
- var cityArray;
- var city=$("cityid");
- var len=city.length;
- //要将城市下拉列表框清空
- if(len!=0){
- city.innerHTML="";
- }
- //如果应答字符串含有"#"号的话进行分割,并将其内容动态的添加到城市下拉列表框中
- if(xmlHttp.responseText.indexOf("#")!=-1){
- cityArray=xmlHttp.responseText.split("#");
- for(var i=0;i<cityArray.length;i++){
- var option=new Option(cityArray[i],cityArray[i]);
- city.add(option);
- }
- }
- else{
- cityArray=xmlHttp.responseText;
- var option=new Option(cityArray,cityArray);
- city.add(option);
- }
- } else {
- alert("请求的出错啦!");
- }
- }
- }
- // --></mce:script>
- <body>
- <form>
- 选择省份:
- <select id="provinceid" οnchange="getCity()">
- <option value="none">
- 请选择
- </option>
- <option value="guangdong">
- 广东
- </option>
- <option value="ningxia">
- 宁夏
- </option>
- </select>
- 城市:
- <select id="cityid">
- <option value="none">
- 没有数据
- </option>
- </select>
- </form>
- </body>
- </html>
(2)GetCity.java
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class GetCity extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.reset();
- String name=request.getParameter("provinceName")==null?"":request.getParameter("provinceName");
- System.out.print(name);
- String str="";
- if(name.trim().equals("guangdong")){
- str="广州#深圳#东莞#中山#珠海#惠东";
- }else if(name.trim().equals("ningxia")){
- str="银川#吴忠#中卫#中宁#固原";
- }else{
- str="没有数据";
- }
- response.setContentType("text/html");
- response.setCharacterEncoding("utf-8");
- response.getWriter().write(str);
- response.getWriter().flush();
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request,response);
- }
- }
(3)web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.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>GetCity</servlet-name>
- <servlet-class>GetCity</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>GetCity</servlet-name>
- <url-pattern>/GetCity</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>