加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax+XML实现级联下拉菜单的动态加载

发布时间:2020-12-16 01:28:37 所属栏目:百科 来源:网络整理
导读:整个业务的流程: 客户端发送请求 → 业务层取出数据 → Servlet生成DOM树回应客户端 → 客户端接收XML数据 → 进行下拉菜单的动态加载 业务层用来取出所有的省份,通过省份 id 取出对应的所有城市,其中的操作省略,直接奔正题(原生操作,不使用框架): sho

整个业务的流程:
客户端发送请求 → 业务层取出数据 → Servlet生成DOM树回应客户端 → 客户端接收XML数据 → 进行下拉菜单的动态加载

业务层用来取出所有的省份,通过省份id取出对应的所有城市,其中的操作省略,直接奔正题(原生操作,不使用框架):

show.html(显示页):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>级联菜单_省份-城市</title>
<script type="text/javascript" src="js/show.js"></script>
</head>
<body>
    <div>
        省份:<select id="area" name="area">
            <option value="0">=== 请选择省份 ===</option>
        </select>
        城市:<select id="areaplus" name="areaplus">
            <option value="0">=== 请选择城市 ===</option>
        </select>
    </div>
</body>
</html>

show.js(js中实现Ajax与XML的交互):

// 页面加载时的事件处理
window.onload = function(){
    area() ;
    document.getElementById("area").addEventListener("change",function(){
        areaplus(this.value) ;
    },false) ;
}

// 定义Ajax操作对象
var xmlHttpRequest ;
// 定义可重用的Ajax操作方法,用来加载相应的数据
function load(urlMsg){
    // 将Ajax操作对象取出
    xmlHttpRequest = new XMLHttpRequest() ;
    console.log("测试Ajax操作对象" + xmlHttpRequest) ;
    // 设置请求并发送
    xmlHttpRequest.open("post",urlMsg) ;
    xmlHttpRequest.send(null) ;
}
// 利用Ajax进行数据的处理,完成页面内容的填充
function getContent(urlMsg,selId,id,title){
    load(urlMsg) ;
    xmlHttpRequest.onreadystatechange = function(){
        // 当服务器端完成请求的处理时
    if (xmlHttpRequest.readyState == 4 || xmlHttpRequest.status == 200){
        // 是城市菜单时要先清空之前的菜单内容
        if (selId == "areaplus"){
            clear() ;
        }
        // 取得对应的XML数据
        var xmlData = xmlHttpRequest.responseXML ;
        // 获取下拉列表框对象
        var select = document.getElementById(selId) ;
        // 取得XML数据中的所有id和title
        var idList = xmlData.getElementsByTagName(id) ;
        var titleList = xmlData.getElementsByTagName(title) ;
        // 创建所有的option并配置到下拉菜单中
        for (var i = 0 ; i < idList.length ; i ++){
            var option = document.createElement("option") ;
            option.setAttribute("value",idList[i].firstChild.nodeValue) ;
            option.appendChild(document.createTextNode(titleList[i].firstChild.nodeValue)) ;
            select.appendChild(option) ;
            }
        }
    }
}
// 显示所有的省份到下拉菜单中
function area(){
    getContent("AreaServlet","area","aid","title") ;
}
// 通过省份的下拉菜单动态显示所有的城市到下拉菜单中
function areaplus(aid){
    if (aid == "0"){ 
        // 如果没有选择省份数据时清空城市下拉列表
        clear() ;
    }else{
        // 进行内容显示的一系列操作,交给getContent()方法
        getContent("AreaplusServlet?aid=" + aid,"areaplus","apid","title") ;
    }
}
// 清空数据
function clear(){
    // 获取城市的下拉菜单对象,用来删除
    var select = document.getElementById("areaplus") ;
    // 由下拉菜单获取所有的option
    var optionList = select.getElementsByTagName("option") ;
    // 取得option的数量,遍历执行删除
    var len = optionList.length ;
    for (var i = 0 ; i < len - 1 ; i ++){
        select.removeChild(optionList[1]) ;
    }
}

AreaServlet(省份处理):

@WebServlet("/AreaServlet")
public class AreaServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException {
        this.doPost(request,response);
    }
    protected void doPost(HttpServletRequest request,IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/xml");
        IAreaService areaService = ServiceFactory.getInstance(AreaServiceImpl.class);
        try {
            // 从数据层取出所有的Area
            List<Area> allArea = areaService.list();
            // 使用DOM4J取出Area内容,并最终生成XML传到前台
            Document document = DocumentHelper.createDocument();
            // 创建根节点
            Element areasEle = document.addElement("areas");
            // 从allArea中取出所有的值对象,设置到每个area节点中
            for (Area areaVO : allArea) {
                // 创建子节点,对子节点的创建一定要放在遍历代码块中,因为节点的数量随着值对象的数量而改变
                Element area = areasEle.addElement("area");
                Element aid = area.addElement("aid");
                Element title = area.addElement("title");
                aid.setText(String.valueOf(areaVO.getAid()));
                title.setText(areaVO.getTitle());
            }
            // XML设置完成后,开始进行一些列操作,将数据向前台输出
            OutputFormat output = OutputFormat.createCompactFormat();
            output.setEncoding("UTF-8");
            // 设置输出位置为客户端(前台)
            XMLWriter writer = new XMLWriter(response.getWriter(),output);
            // 进行XML的输出
            writer.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

AreaplusServlet(城市处理):

@WebServlet("/AreaplusServlet")
public class AreaplusServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,response);
    }
    @Override
    protected void doPost(HttpServletRequest request,IOException {
        request.setCharacterEncoding("UTF-8") ;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/xml");
        IAreaplusService areaplusService = ServiceFactory.getInstance(AreaplusServiceImpl.class) ;
        try {
            // 取出所有的城市数据,取之前要先从客户端接收身份编号
            Integer aid = Integer.parseInt(request.getParameter("aid")) ;
            List<Areaplus> allAreaplus = areaplusService.listByArea(aid) ;
            // 使用DOM4J生成DOM树,输出XML数据到客户端(前台)
            Document document = DocumentHelper.createDocument() ;
            // 创建根节点
            Element areaplusRoot = document.addElement("areapluss") ;
            // 为所有的areaplus创建子节点,首先要迭代所有的areaplus
            Iterator<Areaplus> iter = allAreaplus.iterator();
            while(iter.hasNext()){
                Areaplus vo = iter.next() ;
                // 开始子节点的创建和配置
                Element areaplus = areaplusRoot.addElement("areaplus") ;
                Element apid = areaplus.addElement("apid") ;
                Element title = areaplus.addElement("title") ;
                // 设置每个节点的内容
                apid.setText(String.valueOf(vo.getApid()));
                title.setText(vo.getTitle());
            }
            // DOM树生成之后,开始进行一系列的操作完成对客户端的数据传输
            OutputFormat output = OutputFormat.createCompactFormat() ;
            output.setEncoding("UTF-8");
            // 获取流对象,通过构造设置输出位置到客户端,并设置传输方式为紧凑方式和UTF-8的编码方式
            XMLWriter writer = new XMLWriter(response.getWriter(),output) ;
            // 进行内容的输出
            writer.write(document); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读