Ajax实现动态的二级级联菜单

博客地址:http://www.cnblogs.com/likailan/p/3328761.html

二:ajax实现级联菜单

前台页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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">
<script type="text/javascript" src="js/js.js"></script>
<title>Insert title here</title>
</head>
<body>
    <select id="district" onchange="cascade(this.value)" >
        <option value="-1">请选择</option>
        <c:forEach items="${districts }" var="district">
            <option value="${district.id }">${district.name }</option>
        </c:forEach>
    </select>
    <select id="street" onchange="alert(this.value)">
        <option>请选择</option>
    </select>
</body>
</html>

 js:

//XMLHttpRequest组件
var xhs;
//区域菜单的值发生改变时调用该方法,并把区域菜单当前的value传递进来
function cascade(id){
    //当id不大于0时,说明当前选择的是“请选择”这一项,则不做操作
    if(id>0){
        //请求字符串,把区域的id作为页面参数传到后台
        var url="cascade?id="+id;
        //创建XMLHttpRequest组件
        xhs=new XMLHttpRequest();
        //设置回调函数,processReuqest方法的定义在下面
        xhs.onreadystatechange=processReuqest;
        //打开与服务器的地址连接
        xhs.open("post", url, true);
        //发送请求
        xhs.send(null);
    }
}

//processReuqest方法作为回调方法
function processReuqest(){
    if(xhs.readyState==4){
        if(xhs.status==200){
            //创建新的select节点
            var newSelect=document.createElement("select");
            newSelect.id="street";
            //为新创建的select节点添加onchange事件,以便测试用
            newSelect.onchange=function test(){
                alert(this.value);
            };
            //为新创建的select节点添加option节点
            var op=document.createElement("option");
            op.value=-1;
            op.innerHTML="请选择";
            newSelect.appendChild(op);
            //得到完成请求后返回的字串符
            var str = xhs.responseText;
            //根据返回的字符串为新创建的select节点添加option节点
            var arr1=str.split(",");
            for(var i=0;i<arr1.length;i++){
                var arr2=arr1[i].split("=");
                var child=document.createElement("option");
                child.innerHTML=arr2[1];
                child.value=arr2[0];
                newSelect.appendChild(child);
            }
            //用新select节点替换旧的select节点
            var select = document.getElementById("street");
            document.body.replaceChild(newSelect, select);
        }
    }
}
function createXmlHttpRequest(){
    if(window.ActiveXObject){
        return new ActiveXObject("Microsoft.XMLHTTP");
    }else if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    }
}

 servlet

package cascade.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import cascade.entity.District;
import cascade.entity.Street;
import cascade.service.StreetService;


public class CascadeServlet extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        int id =Integer.parseInt(req.getParameter("id"));
        District district=new District();
        district.setId(id);
        
        /*
         * StreetService  ss为操作数据库的对象.
         * 调用该对象的getAllStreet()方法,可以从数据库中取得所有的区域信息,封装为List<Street>对象,并返回。
         * 其中Street是数据库Street表的实体类 
         * 为了把重点放在Ajax和级联菜单的实现上,本文省略了操作数据库的代码!!!
         */
        StreetService ss=new StreetService();
        List<Street> streets=ss.getAllStreet(district);
        //把得到的街道对象集合拼接成字符串文本
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<streets.size();i++){
            sb.append(streets.get(i).getId()).append("=").append(streets.get(i).getName());
            if(i!=streets.size()-1){
                sb.append(",");
            }
        }
        //servlet不转向或重定向到任何页面,使用resp.getWriter().print()方法可以把文本响应给XMLHttpRequest对象
         PrintWriter out = resp.getWriter();
         out.print(sb.toString());
         out.flush();
         out.close();
    }
    
}

相关推荐