Ajax实现省市二级联动(源代码)

 1 、实现省市的二级无刷新联动选择省名连接服务器动态加载市名(list.jsp)

<%@ page language="java" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>省市联动</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">
 <script type="text/javascript">
  var xhr;
  function change(provinceId){
      //如果选择"==请选择==" 清空城市下拉列表
   if(provinceId=='0'){
    clearCity();
    return;
   }
   //创建XMLHttpRequest对象
   createXmlHttp();
   //设置回调函数
   xhr.onreadystatechange = response;
   //初始化
   xhr.open('GET','ListServlet.do?provinceId='+provinceId,true);
   //设置不使用缓存
   xhr.setRequestHeader("If-Modified-Since","0");
   //发送请求
   xhr.send(null);
  }
  
  function response(){
   var city = document.getElementById("city");
   if(xhr.readyState == 4 && xhr.status == 200 ){
    var s = xhr.responseText;
    var citys = s.split(",");
    clearCity();
    for(var i=0;i<citys.length;i++){
     city.options[city.options.length] = new Option(citys[i],citys[i]);
    }
   }
  }
   
     function createXmlHttp(){
      //非IE浏览器创建XmlHttpRequest对象
       if(window.XmlHttpRequest){
        xhr = new XmlHttpRequest();
      }
      //IE浏览器创建XmlHttpRequest对象
      if(window.ActiveXObject){
        try{
         xhr = new ActiveXObject("Microsoft.XMLHTTP");    
        }catch(e){
         xhr = new ActiveXObject("msxml2.XMLHTTP");
        }
      }
     }
  
  //清空城市下拉列表
  function clearCity(){
   var city = document.getElementById("city");
   city.options.length = 0;
   city.options[0] = new Option('==请选择==','0');
  }
  
 </script>
  </head>
 
  <body>
    <h1>省市联动</h1><hr>
    <h3>Where Are You From ?</h3>
    省份:<select id="province" οnchange="change(this.value)">
      <option value="0">==请选择==</option>
      <option value="1">浙江</option>
      <option value="2">江苏</option>
      <option value="3">湖北</option>
      <option value="4">湖南</option>
      <option value="5">广东</option>
        </select>
    城市:<select id="city">
      <option>==请选择==</option>
        </select>
  </body>
</html>
2、处理逻辑的servlert类 ListServlet.java

package com.test.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ListServlet  extends HttpServlet {

 private static final long serialVersionUID = 1L;
 public static Map<String,List<String>> map= new HashMap<String,List<String>>();
 
 public void init() throws ServletException{
  List<String> list = new ArrayList<String>();
  list.add("杭州");
  list.add("绍兴");
  list.add("宁波");
  list.add("台州");
  map.put("1", list);
  list = new ArrayList<String>();
  list.add("南京");
  list.add("苏州");
  list.add("常州");
  list.add("无锡");
  map.put("2", list);
  list = new ArrayList<String>();
  list.add("武汉");
  list.add("鄂州");
  list.add("荆州");
  list.add("十堰");
  map.put("3", list);
  list = new ArrayList<String>();
  list.add("长沙");
  list.add("岳阳");
  list.add("常德");
  list.add("张家界");
  map.put("4", list);
  list = new ArrayList<String>();
  list.add("广州");
  list.add("珠海");
  list.add("深圳");
  list.add("东莞");
  map.put("5", list);
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
  String provinceId = request.getParameter("provinceId");
  List<String> list = map.get(provinceId);
  StringBuffer sb = new StringBuffer();
  if(list!=null){
   for(String s: list) {
    sb.append(s).append(",");
   }
   if(!list.isEmpty()){
    sb.deleteCharAt(sb.length()-1);
   }
  }
  
  response.setContentType("test/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  out.print(sb.toString());
  out.close();
 }

 protected 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.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>
      <servlet-name>myServlet</servlet-name>
      <servlet-class>com.test.ajax.ListServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>myServlet</servlet-name>
      <url-pattern>/ListServlet.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>list.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 4、截图显示

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值