Ajax技术--多级联动下拉列表($.ajax())

本文介绍了一种使用XML文件存储区域数据,并通过Java Servlet结合DOM4J进行数据解析的方法。实现了网页上省份、城市及区县的动态加载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

运行结果:


1、设置zone.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
<country>
  <province id = "00000" name = "北京市">
    <city id = "00001" name = "北京市" area = "东城区,西城区,朝阳区,丰台区,石景山区,海淀区,门头沟区,房山区,
    通州区,顺义区,昌平区,大兴区,怀柔区,平谷区,密云县,延庆县">
    </city>
  </province>
  
  <province id = "00005" name = "吉林省">
    <city id = "05001" name = "长春" area = "双阳区,得回区,九台市,农安县,榆树市,南关区,宽城区,超验去,高新区"></city>
    <city id = "05006" name = "四平" area = "梨树县,公主岭市,双辽市"></city>
  </province>
  
  <province id = "00006" name = "四川省">
    <city id ="06001" name = "成都市" area = "双流区,青白区,武侯区,金堂县,金牛区,新都区,郫县区,温江区,新津县"></city>
    <city id = "06002" name = "绵阳市" area = "三台县,江油市,绵竹市,梓潼县,罗江县,安州区"></city>
    <city id = "06003" name = "攀枝花市" area = "东区,西区,米易县,盐边县,仁和区"></city>
  </province>
</country>


2、index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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 'index.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">
	-->
	
	<script type="text/javascript" src = "js/jquery-3.1.1.min.js"></script>
	
	<script type="text/javascript">
	  //获取省份和直辖市
	  function getProvince(){
	    $.ajax({
	      url:"ZoneServlet?action=getProvince&nocache="+new Date().getTime(),
	      //设置请求成功时的回调函数
	      success:function(data){
	        var provinceList = data.split(",");
	        for(var i = 0; i < provinceList.length; i++){
	          $("#province").append("<option vlaue = '" + provinceList[i] + "'>"+provinceList[i]+
	          "</option>");
	        }
	        
	        if(provinceList != ""){
	         getCity(provinceList[0]);//获取地级市
	        }
	      }
	    });
	  }
	  
	  $(document).ready(function(){
	    getProvince();
	  });
	  
	  //获取地级市
	  function getCity(province){
	    $.ajax({
	    url:"ZoneServlet?action=getCity&province="+ province +"&nocache="+new Date().getTime(),
	    success:function(data){
	        var cityList = data.split(",");
	        $("#city").empty(); //必须清空下拉列表
	        for(var i = 0; i < cityList.length; i++){
	          $("#city").append("<option vlaue = '" + cityList[i] + "'>"+cityList[i]+
	          "</option>");
	        }	  
          if(cityList != ""){
            getArea(province,cityList[0]);
          } 
	    }
	    });
	  }
	  
	  
	  //获取县/区
	  function getArea(province,city){
	    $.ajax({
	     url:"ZoneServlet?action=getArea&province="+ province +"&city="+ city +"&nocache="+new Date().getTime(),
	     success:function(data){
	       $("#area").empty();//清空列表
	       var areaList = data.split(",");
	       for(var i = 0; i < areaList.length; i++){
	         $("#area").append("<option value = '"+ areaList[i] +"'>"+ areaList[i] +"</option>");
	       }
	     }
	    });
	  }
	  
	</script>
  </head>
  
  <body>
    <select id = "province" onChange = "getCity(this.value)"></select>
    -
    <select id = "city" onChange = "getArea(document.getElementById('province').value,this.value)"></select>
    -
    <select id = "area"></select>
  </body>
</html>

3、ZoneServlet.java:

引入jar包;dom4j-1.6.1.jar

                jaxen-1.1.1.jar

package Servlet;

import java.util.List;
import java.io.File;
import java.io.FileWriter;
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;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.w3c.dom.ls.LSException;
import org.jaxen.JaxenException; //xPath解析时必须引入

@SuppressWarnings("serial")
public class ZoneServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String action = request.getParameter("action");
		if("getProvince".equals(action)){
					getProvince(request,response);
		}else if("getCity".equals(action)){
			getCity(request,response);
		}else if("getArea".equals(action)){
			getArea(request,response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}


	@SuppressWarnings("unchecked")
	public void getProvince(HttpServletRequest request,HttpServletResponse response) 
			throws ServletException, IOException{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
        String fileURL = request.getRealPath("/XML/zone.xml");
        File file = new File(fileURL);
        Document document = null;
        Element country = null;
        String result = "";
        if(file.exists()){
        	SAXReader reader= new SAXReader();
        	try {
				document = reader.read(file);
        	country = document.getRootElement();
			List<Element> provinceList = country.elements("province");
			Element provincElement = null;
			for (int i = 0; i < provinceList.size(); i++) {
				provincElement = provinceList.get(i);
				result = result + provincElement.attributeValue("name")+",";
			}
			result = result.substring(0, result.length()-1);
          } catch (Exception e) {
			System.out.println("getProvince");
		    }     
        }
        else {
        	System.out.println("file not found");
        }
        out.println(result);
		out.flush();
		out.close();
	}
	

	public void getCity(HttpServletRequest request,HttpServletResponse response) 
			throws ServletException, IOException{
            response.setContentType("text/html;charset=utf-8");
            String selprovince = new String(request.getParameter("province").getBytes("iso-8859-1"),"utf-8");
            
            Document document = null;
            Element country = null;
            String result = "";
            String urlString = request.getRealPath("/XML/zone.xml");
            File file= new File(urlString);
            if(file.exists()){
            	SAXReader reader = new SAXReader();
                try {
					document = reader.read(file);
					country = document.getRootElement();
					Element item = (Element) country.selectSingleNode("/country/province[@name='"+ selprovince +"']");
				    List<Element> listCity = item.elements("city");
				    for (int i = 0; i < listCity.size(); i++) {
						Element city = listCity.get(i);
						result = result + city.attributeValue("name")+",";
					}
				    result = result.substring(0,result.length()-1); //去掉最后一个逗号
                } catch (DocumentException e) {
				}
                
            }else {
            	System.out.println("getCity_file not exist");
            }
    		PrintWriter out = response.getWriter();
            out.println(result);
    		out.flush();
    		out.close();
	}
	

	private void getArea(HttpServletRequest request,HttpServletResponse response) 
			throws ServletException, IOException{
		response.setContentType("text/html;charset=utf-8");
		String urlString = request.getRealPath("/XML/zone.xml");
		Document document = null;
		Element country = null;
		File file = new File(urlString);
		String result = "";
		if(file.exists()){
			SAXReader reader = new SAXReader();
			try {
				document = reader.read(file);
				country = document.getRootElement();
				String selProvince = new String(request.getParameter("province").getBytes("iso-8859-1"),"utf-8");
				String selCity = new String(request.getParameter("city").getBytes("iso-8859-1"),"utf-8");
				Element province = (Element) country.selectSingleNode("/country/province[@name='"+ selProvince +"']"); //获取省/直辖市节点
				Element city = (Element) province.selectSingleNode("city[@name='"+ selCity +"']");  //获取城市节点
			    result = city.attributeValue("area");
			} catch (DocumentException e) {}
		}else {
			System.out.println("getArea_file not exists");
		}
		PrintWriter out = response.getWriter();
        out.println(result);
		out.flush();
		out.close();		
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值