用JSP+JavaScript打造三级级联下拉菜单

mssqlserver 数据库 db_Database02
CREATE TABLE [dbo].[tb_Area] (
 [ID] [int] NOT NULL ,
 [Name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
 [TypeID] [int] NOT NULL ,
 [Father] [int] NULL
) ON [PRIMARY]
GO

源文件
com.core
ChStr.java
package com.core;
public class ChStr {
/***************************************************
 *功能:解决输出中文乱码问题,返回值为String
***************************************************/
        public String chStr(String str){
           if(str==null){
                str="";
           }else{
                try{
str=(new String(str.getBytes("iso-8859-1"),"GB2312")).trim();
              }catch(Exception e){
                   e.printStackTrace(System.err);
              }
           }
           return str;
         }
/***************************************************
 *功能:显示文本中的回车换行、空格,返回值为String
***************************************************/
       public String convertStr(String str1){
           if(str1==null){
            str1="";
          }else{
            try{

              str1=str1.replaceAll(" "," ");
              str1=str1.replaceAll("/r/n","<br>");
            }catch(Exception e){
                   e.printStackTrace(System.err);
            }
         }
         return str1;
     }
}


ConnDB.java
package com.core;

import java.sql.*;
public class ConnDB{
                Connection conn=null;
                Statement stmt=null;
                ResultSet rs=null;
        public ConnDB(){
                try{
                        Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                }catch(java.lang.ClassNotFoundException e){
                        System.err.println(e.getMessage());
                }
        }
 /***************************************************
        *method name: executeQuery()
        *功能:执行查询操作
        *return value: ResultSet
****************************************************/
        public ResultSet executeQuery(String sql){
                try{
                        conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_database02;user=sa;password=sa");
                        stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
                        rs=stmt.executeQuery(sql);
                }catch(SQLException ex){
                        System.err.println(ex.getMessage());
                        }finally{}
                return rs;
        }
/***************************************************
         *method name: executeUpdate()
         *功能:执行更新操作
         *return value: int
****************************************************/

        public int executeUpdate(String sql){
                int result=0;
                try{
                        conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_database02;user=sa;password=");
                        stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
                        result=stmt.executeUpdate(sql);
                }catch(SQLException ex){
                        result=0;
                        }finally{}
                return result;
        }
 /***************************************************
        *method name: close()
        *功能:关闭数据库链接
        *return value:  void
****************************************************/
       public void close(){
         try {
           if (rs != null) rs.close();
         }
         catch (Exception e) {
           e.printStackTrace(System.err);
         }finally{}
         try {
           if (stmt != null) stmt.close();
         }
         catch (Exception e) {
           e.printStackTrace(System.err);
         }finally{}
         try {
           if (conn != null) {
             conn.close();
           }
         }
         catch (Exception e) {
           e.printStackTrace(System.err);
         }finally{}
       }
}

index.jsp(级联的重点)
<%@page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage=""%>
<jsp:useBean id="connDB" class="com.core.ConnDB" scope="page"/>
<%
  ResultSet rs_city = null;
  ResultSet rs_Town = null;
  ResultSet rs_province = null;
  String sql = "";
  String sql_T = "";
  int SelectID_C = 0;
  int SelectID_P=0;
  String strCityID1=request.getParameter("CityID");
  String strSelectID_P=request.getParameter("ProvinceID");
  if (strSelectID_P!=null &&!strSelectID_P.equals("")) {
    session.setAttribute("SelectID_P", strSelectID_P);
  }
  String sql_P = "SELECT *  FROM tb_Area  WHERE TypeID=1 or TypeID=4 or TypeID=5";
  try {
    rs_province = connDB.executeQuery(sql_P);
    if (rs_province.next()) {
      if(session.getAttribute("SelectID_P")!=null){
        SelectID_P= Integer.parseInt((String)session.getAttribute("SelectID_P"));
      }else{
        SelectID_P=rs_province.getInt("ID");
      }
      %>
      <html>
      <head>
      <title>级联菜单</title>
      <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
        <link href="style.css" _fcksavedurl=""style.css"" _fcksavedurl=""style.css"" rel="stylesheet">
        <style type="text/css">
        <!--
        body {
        margin-left: 0px;
        margin-top: 0px;
        background-image:  url(Images/bg.gif);
        }
        .style1 {color: #FFFFFF}
        .style2 {color: #a2bcc5}
        -->
        </style>
      </head>
      <script language="javascript">
      function ChangeItem_P(){
        var ProvinceID=form1.Province.value;
        window.location.href="index.jsp?ProvinceID="+ProvinceID;           //缺点:取父结点的值时要转发页面.
      }
      </script>
      <script language="javascript">
      function ChangeItem_C(){
        var CityID=form1.city.value;
        window.location.href="index.jsp?CityID="+CityID;
      }
      </script>
      <body>
      <table width="400" height="242" border="0" cellpadding="-2" cellspacing="-2" background="Images/add.gif">
        <tr>
          <td valign="top">
            <table width="400" height="271" cellpadding="-2" cellspacing="-2">
              <tr>
                <td width="11" height="85">&nbsp;</td>
                <td width="373">&nbsp;</td>
                <td width="14">
                  <span class="style2"></span>
                </td>
              </tr>
              <tr>
                <td height="144">&nbsp;</td>
                <td valign="top">
                  <div align="center">
                    <form name="form1" method="post" action="">
                    <table width="88%" height="142" border="1" cellpadding="-2" cellspacing="-2" bordercolor="#669999" bordercolordark="#FFFFFF">
                      <tr>
                        <td width="32%" height="27" bgcolor="#809EA4">
                          <div align="center" class="style1">省级名称:</div>
                        </td>
                        <td width="68%">
                        <%
                        sql = "select* from tb_area where TypeID=2 and father=" + SelectID_P + "";
                        sql_T = "select* from tb_area where TypeID=3 and father=" + SelectID_P + "";
                        rs_city = connDB.executeQuery(sql);
                        rs_Town = connDB.executeQuery(sql_T);
                        %>
                        <div align="left">                      &nbsp;
                          <select name="Province" onChange="ChangeItem_P()">
                          <%
                          rs_province.first();
                          do {
                            %>
                            <option value="<%=rs_province.getInt("ID")%>" <%if(rs_province.getInt("ID")==SelectID_P){out.print("selected");} %>><%=rs_province.getString("Name")%> </option>
                            <%
                            } while (rs_province.next()) ;
                            %>
                            </select>
                        </div>
                        </td>
                      </tr>
                      <tr>
                        <td height="27" bgcolor="#809EA4">
                          <div align="center" class="style1">市/县名称:</div>
                        </td>
                        <td>
                          <div align="left">                      &nbsp;
                            <%if (rs_city.next()) {
                            if (strCityID1==null) {
                              SelectID_C=rs_city.getInt("ID");
                            }else{
                              SelectID_C = Integer.parseInt(request.getParameter("CityID"));
                            }
                            %>
                            <select name="city" onChange="ChangeItem_C()">
                            <%rs_city.first();
                            do {
                              %>
                              <option value="<%=rs_city.getInt("ID")%>" <%if(rs_city.getInt("ID")==SelectID_C){%>selected<%}%>><%=rs_city.getString("Name")%>                        </option>
                              <%
                              } while (rs_city.next());
                              %>
                              </select>
                          </div>
                          <%} else {                    %>
                          <select name="city" onChange="ChangeItem_C()">
                            <option value="0">---</option>
                          </select>
 </div>
<%
}
%>
</td>
                      </tr>
                      <tr>
                        <td height="27" bgcolor="#809EA4">
                          <div align="center" class="style1">区/镇/乡名称:</div>
                        </td>
                        <td>
                        <%
                        if (SelectID_C != 0) {  //选择了市县级名称
                        sql_T = "select* from tb_area where father=" + SelectID_C + "";
                        System.out.println("sql_T!=0:"+sql_T);
                        rs_Town = connDB.executeQuery(sql_T);
                      }
                      %>
                      <%if (rs_Town.next()) {%>
                      <div align="left">                      &nbsp;
                        <select name="town" id="select5">
                        <%rs_Town.first();
                        do { %>
                        <option value="<%=rs_Town.getInt("ID")%>"><%=rs_Town.getString("Name")%></option>
                        <%
                        } while (rs_Town.next());
                        %>
                        </select>
                      </div>
                      <%} else {                  %>
                      <div align="left"> &nbsp;
                        <select name="town" id="select5">
                          <option value="0">---</option>
                        </select>
                      </div>
                      <%}  %>
                        </td>
                      </tr>
                      <tr>
                        <td height="33" colspan="2">
                          <div align="center">
                            <input name="Submit" type="submit" class="Style_button" value="删除">
                            <input name="Button" type="button" class="Style_button" value="关闭" onClick="javascrip:window.close()">
                          </div>
                        </td>
                      </tr>
                    </table>
                    </form>
</div>
                </td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>          </td>
                <td>&nbsp;</td>
              </tr>
            </table>
</td>
        </tr>
      </table>
      </body>
      </html>
      <%
      }
  } catch (Exception e) {
    System.out.println("查询省级名称时出错:"+e.getMessage());
  }
%>

style.css
<!--
td           { font-size: 9pt;font_name:宋体;; line-height: 16pt}
a:hover      { color: #00D8FF; text-decoration: underline; font-size: 9pt }
a            { font-size: 9pt; color: #708E98; text-decoration: none }
p {  font-size: 9pt; font-family: "宋体"; line-height: 11pt}
.dt { font-size:9pt}
INPUT.Style_button {
 BORDER-RIGHT: #527184 1px solid; BORDER-TOP: #527184 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 9pt; BACKGROUND: #A2BCC5; BORDER-LEFT: #527184 1px solid; COLOR: #ffffff; LINE-HEIGHT: normal; BORDER-BOTTOM: #527184 1px solid; FONT-STYLE: normal; HEIGHT: 17px;width: 40px; FONT-VARIANT: normal
}
INPUT.Sytle_text {
 BORDER-RIGHT: #A2BCC5 1px solid; BORDER-TOP: #A2BCC5 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 9pt; BORDER-LEFT: #A2BCC5 1px solid; LINE-HEIGHT: normal; BORDER-BOTTOM: #A2BCC5 1px solid; FONT-STYLE: normal; width:82px; HEIGHT: 16px; FONT-VARIANT: normal
}
INPUT.Sytle_auto {
 BORDER-RIGHT: #A2BCC5 1px solid; BORDER-TOP: #A2BCC5 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 9pt; BORDER-LEFT: #A2BCC5 1px solid; LINE-HEIGHT: normal; BORDER-BOTTOM: #A2BCC5 1px solid; FONT-STYLE: normal; HEIGHT: 16px; FONT-VARIANT: normal
}
INPUT.Style_subject {
 BORDER-RIGHT: #A2BCC5 1px solid; BORDER-TOP: #A2BCC5 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 9pt; BORDER-LEFT: #A2BCC5 1px solid; LINE-HEIGHT: normal; BORDER-BOTTOM: #A2BCC5 1px solid; FONT-STYLE: normal; HEIGHT: 18px; Width: 390px; FONT-VARIANT: normal
}
INPUT.Style_button_del {
 BORDER-RIGHT: #527184 1px solid; BORDER-TOP: #527184 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 9pt; BACKGROUND: #A2BCC5; BORDER-LEFT: #527184 1px solid; COLOR: #ffffff; LINE-HEIGHT: normal; BORDER-BOTTOM: #527184 1px solid; FONT-STYLE: normal; HEIGHT: 17px;width: 100px; FONT-VARIANT: normal
}
INPUT.Style_nj {
 BORDER-RIGHT: #A2BCC5 1px solid; BORDER-TOP: #A2BCC5 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 9pt; BORDER-LEFT: #A2BCC5 1px solid; LINE-HEIGHT: normal; BORDER-BOTTOM: #A2BCC5 1px solid; FONT-STYLE: normal; HEIGHT: 18px; Width: 362px; FONT-VARIANT: normal
}
INPUT.Style_upload {
 BORDER-RIGHT: #A2BCC5 1px solid; BORDER-TOP: #A2BCC5 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 9pt; BORDER-LEFT: #A2BCC5 1px solid; LINE-HEIGHT: normal; BORDER-BOTTOM: #A2BCC5 1px solid; FONT-STYLE: normal; HEIGHT: 18px; Width: 290px; FONT-VARIANT: normal
}
INPUT.Style_button_P {
 BORDER-RIGHT: #527184 1px solid; BORDER-TOP: #527184 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 9pt; BACKGROUND: #A2BCC5; BORDER-LEFT: #527184 1px solid; COLOR: #ffffff; LINE-HEIGHT: normal; BORDER-BOTTOM: #527184 1px solid; FONT-STYLE: normal; HEIGHT: 17px;width: 60px; FONT-VARIANT: normal
}
-->

 

 

 这种方法的缺点就是
取父结点的值的时候要转发页面.这样又要重新刷新页面.

 

 
实现基于 AJAX 的三级级联下拉菜单,需要使用 servlet 响应 AJAX 请求,动态生成下拉菜单的 HTML 代码,并通过 AJAX 将生成的 HTML 代码返回给前端。 以下是实现基于 AJAX 的三级级联下拉菜单的步骤: 1. 在 JSP 页面中添加三个下拉菜单,分别对应三级级联下拉菜单的三个级别。 2. 使用 JavaScript 监听第一个下拉菜单的 onchange 事件,当第一个下拉菜单的选项改变时,发送 AJAX 请求到 servlet。 3. 在 servlet 中获取第一个下拉菜单的选项值,根据选项值生成第二个下拉菜单的选项,以及第三个下拉菜单的选项所需要的数据。 4. 使用 StringBuilder 动态生成 HTML 代码,并将生成的 HTML 代码返回给前端。 5. 在 JavaScript 中监听 AJAX 的 success 事件,将返回的 HTML 代码插入到第二个和第三个下拉菜单中。 以下是代码示例: Java 代码: ```java @WebServlet("/cascade") public class CascadeServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String parentId = request.getParameter("parentId"); List<Category> categories = getCategoryList(parentId); StringBuilder sb = new StringBuilder(); sb.append("<option value=\"\">请选择</option>"); for (Category category : categories) { sb.append("<option value=\"").append(category.getId()).append("\">").append(category.getName()).append("</option>"); } response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write(sb.toString()); } private List<Category> getCategoryList(String parentId) { // 根据 parentId 获取子分类列表 // ... } } ``` JavaScript 代码: ```javascript $(function() { $("#level1").change(function() { var parentId = $(this).val(); if (parentId == "") { $("#level2").html("<option value=''>请选择</option>"); $("#level3").html("<option value=''>请选择</option>"); return; } $.ajax({ url: "cascade", data: {parentId: parentId}, success: function(response) { $("#level2").html(response); $("#level3").html("<option value=''>请选择</option>"); } }); }); $("#level2").change(function() { var parentId = $(this).val(); if (parentId == "") { $("#level3").html("<option value=''>请选择</option>"); return; } $.ajax({ url: "cascade", data: {parentId: parentId}, success: function(response) { $("#level3").html(response); } }); }); }); ``` JSP 页面代码: ```html <select id="level1"> <option value="">请选择</option> <option value="1">一级分类1</option> <option value="2">一级分类2</option> <option value="3">一级分类3</option> </select> <select id="level2"> <option value="">请选择</option> </select> <select id="level3"> <option value="">请选择</option> </select> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值