jsp二级联动菜单(响应xml格式的字符串)

该博客展示了如何在JSP中通过XML格式的字符串实现二级联动菜单,即省份和城市的选择。首先,从数据库获取省份信息并展示在省份下拉列表中,当选择省份时,通过AJAX发送POST请求到GetCityServlet。Servlet接收到请求后,查询对应的市数据,将结果转换成XML字符串并返回。JavaScript接收响应,解析XML并动态填充城市下拉列表。

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

----------------------jsp页面--------------------

<%@page import="com.neuedu.entity.City"%>
<%@page import="com.neuedu.entity.Province"%>
<%@page import="java.util.List"%>
<%@page import="com.neuedu.service.Userservice"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>
    <%     //在jsp页面中查询数据库得到省份(最好在servlet中写java代码,这里只是为了)
        Userservice uvl = new Userservice();
        List<Province> list = uvl.selectProvince();
        pageContext.setAttribute("list", list);
    %>
    省份:<select id="province" name="province" onChange="getCity()">
        <option value="---" >请选择</option>
        <c:forEach items="${list}" var="pro" varStatus="ind">
            <option name="ce" value="${pro.provinceId}">${pro.province}</option>

        </c:forEach>
    </select>

    城市:<select id="city" name="city">
        <option value="---">请选择</option>
        
    </select>

<script type="text/javascript">
    var xmlHttpRequest = false;
    
    function getCity()
    {
        //1.创建XMLHttpRequest对象
        //非IE浏览器
        if(window.XMLHttpRequest)
        {
            xmlHttpRequest = new XMLHttpRequest();

        }

        else if(window.ActiveXObject)    //IE浏览器
        {
            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if(xmlHttpRequest)
        {
            //获取参数
            var provinceObj = document.getElementById("province");//省份下拉列表对象
            var proId = provinceObj.options[provinceObj.selectedIndex].value;//选中的省份编号
            //2.定义url连接

            var url = "GetCityServlet";

            //3.打开到服务器的连接

            xmlHttpRequest.open("post", url, true);
            //设置请求头---------------POST提交方式必备配置
            xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            //4.绑定回调函数

            xmlHttpRequest.onreadystatechange = callback;

            //5.发送请求

            xmlHttpRequest.send("proId="+proId);
        }
        else
        {
            alert("XMLHttpRequest对象创建失败");
        }
    }
    //回调函数
    function callback()
    {
      
        if(xmlHttpRequest.readyState==4)//响应完成
        {
            if(xmlHttpRequest.status==200) //响应正常 OK
            {    //响应回来的xml格式的城市列表
                var response=xmlHttpRequest.responseXML;
              //获取xml的<cities>根元素
                var root=response.documentElement;
               //根据根元素,获取元素中所有的<city>节点
                var cityList=root.getElementsByTagName("city");
                //遍历cityList,将对应的城市信息绑定到城市下拉列表
                var cityObj=document.getElementById("city");
              //清空下拉列表
                cityObj.length=1;  //设置为1是只保留下拉列表中的(请选择这一条)
                

                for(var i=0;i<cityList.length;i++){   //注意:遍历的条件把i<cityList.length换做i<cityObj.length是可以遍历的,但是前段页面会报错(childNodes没有被定义),这里的i<cityObj.length之所以可以是应为每一次循环都会追加下拉列表的内容,长度也刚好是所要插入的内容的的容量

                    //获取指定下标的城市city对象

                    var city=cityList[i];
                  
                    var cid=city.childNodes[0].firstChild.nodeValue;
                    var cname=city.childNodes[1].firstChild.nodeValue;
                    //绑定到下拉城市列表
                    cityObj.options[cityObj.options.length]=new Option(cname,cid);
                }
            }
        }
    }

</script>
</body>

</html>

------------------------------------------------------------------------

------------------------servlet--------------------------

package com.neuedu.servlet;

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

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

import com.neuedu.entity.City;
import com.neuedu.service.Userservice;

/**
 * Servlet implementation class GetCityServlet
 */
@WebServlet("/GetCityServlet")
public class GetCityServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost_xml(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String proId =request.getParameter("proId");
        System.out.println("proId:"+proId);
        Userservice service=new Userservice();//查询数据库
        List<City> list=service.selectCity(proId);
        
        StringBuffer xml=new StringBuffer();
        
        
        /*
         * 将List转换为xml格式的字符串
         *
         *             <?xml version="1.0" encoding="UTF-8"?>
                    <cities>
                    
                        <city>
                            <cid>1001</cid>
                            <cname>广州市</cname>
                        </city>
                        
                        .......
                        
                    </cities>
         */
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        xml.append("<cities>");
        for (City city : list) {
            xml.append("<city>");
                xml.append("<cid>"+city.getCityId()+"</cid>");
                xml.append("<cname>"+city.getCity()+"</cname>");
            xml.append("</city>");
        }
        xml.append("</cities>");
        //指定响应的编码格式
        response.setCharacterEncoding("utf-8");
        //如果在过滤器中有设置编码格式,最好这里也设置一下(因为在过滤器中可能没有这只xml的响应)
        response.setContentType("text/xml;charset=utf-8");
        //响应回客户端
        PrintWriter writer=response.getWriter();
        writer.write(xml.toString());
        writer.flush();
        writer.close();
        
    }

}

--------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值