Ajax實現多級聯動菜單__Ajax

來源:互聯網
上載者:User

         最近在重溫Ajax技術,就順手拿起了當年的《Ajax經典案例開發大全》來溫習。發現裡面有些錯誤,現在就指出來,這樣可以協助後學者少走彎路。主要的技術有:MySql、JDBC、JSON、Ajax、JSP。其實本文不算原創,主要內容還是摘自《Ajax經典案例開發大全》。

        1.資料庫設計

drop database if exists mydb;create database mydb character set gbk;--多級聯動菜單use mydb;drop table if exists select_menu;create table select_menu(id varchar(255) not null default '',text varchar(255) not null,pid varchar(255) not null,seq int(11) not null default 0,primary key (id))ENGINE=InnoDB DEFAULT CHARSET=gbk;insert into select_menu values('A1','列表A選項1','INIT',1);insert into select_menu values('A2','列表A選項2','INIT',2);insert into select_menu values('B11','列表B選項11','A1',1);insert into select_menu values('B12','列表B選項12','A1',2);insert into select_menu values('B13','列表B選項13','A1',3);insert into select_menu values('B21','列表B選項21','A2',1);insert into select_menu values('B22','列表B選項22','A2',2);insert into select_menu values('C111','列表C選項111','B11',1);insert into select_menu values('C112','列表C選項112','B11',2);insert into select_menu values('C121','列表C選項121','B12',1);insert into select_menu values('C122','列表C選項122','B12',2);insert into select_menu values('C131','列表C選項131','B13',1);insert into select_menu values('C132','列表C選項132','B13',2);insert into select_menu values('C211','列表C選項211','B21',1);insert into select_menu values('C212','列表C選項212','B21',2);insert into select_menu values('C221','列表C選項221','B22',1);insert into select_menu values('C222','列表C選項222','B22',2);


 

        2.串連資料庫的工具類

package com.lanp.ajax.db;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** * 串連資料庫的工具類,被定義成不可繼承且是私人訪問 * @author lanp * @since 2012-2-29 22:27 */public final class DBUtils {private static String url = "jdbc:mysql://localhost:3306/mydb?characterEncoding=gbk";private static String user = "root";private static String psw = "root";private static  Connection conn;static {try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {e.printStackTrace();throw new RuntimeException(e);}}private DBUtils() {}/** * 擷取資料庫的串連 * @return conn */public static Connection getConnection() {try {conn = DriverManager.getConnection(url, user, psw);} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}return conn;}/** * 釋放資源 * @param conn * @param pstmt * @param rs */public static void closeResources(Connection conn,PreparedStatement pstmt,ResultSet rs) {if(null != rs) {try {rs.close();} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);} finally {if(null != pstmt) {try {pstmt.close();} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);} finally {if(null != conn) {try {conn.close();} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}}}}}}}}


 

        3.select_menu.html頁面

<!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>多級聯動菜單</title><script type="text/javascript">var xmlHttp;//用於儲存XMLHttpRequest對象的全域變數var targetSelId;//用於儲存要更新選項的列表IDvar selArray = new Array();//用於儲存串聯功能表ID的數組,《Ajax經典案例開發大全》中沒有= new Array()代碼//用於建立XMLHttpRequest對象function createXmlHttp() {if(window.XMLHttpRequest) {xmlHttp = new XMLHttpRequest();} else {xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}}//擷取列表選項的調用函數function buildSelect(selectedId,targetId) {if("" == selectedId) {//selectedId為空白串表示選中了預設項clearSubSel(targetId);//清楚目標列表及下級列表中的值return;//直接結束調用,不必向伺服器請求資訊}targetSelId = targetId;//將傳入的目標列表ID賦值給targetSelId變數createXmlHttp();//建立XMLHttpRequest對象xmlHttp.onreadystatechange = buildSelectCallBack;//設定回呼函數xmlHttp.open("GET", "select_menu.jsp?selectedId="+selectedId, true);xmlHttp.send(null);}//擷取列表選項的回呼函數function buildSelectCallBack() {if(4 == xmlHttp.readyState) {//將從伺服器獲得的文本轉為對象直接量var optionsInfo = eval("(" + xmlHttp.responseText + ")");var targetSelNode = document.getElementById(targetSelId);clearSubSel(targetSelId);//遍曆對象直接量中的成員for(var o in optionsInfo) {//在目標列表追加新的選項targetSelNode.appendChild(createOption(o,optionsInfo[o]));}}}//根據傳入的value和text建立選項function createOption(value,text) {var opt = document.createElement("option");//建立一個option節點opt.setAttribute("value", value);//設定valueopt.appendChild(document.createTextNode(text));//給節點加入文本資訊return opt;}//清除傳入的列表節點內所有選項function clearOptions(selNode) {selNode.options.length = 1;selNode.options[0].selected = true;}//初始化列表數組,《Ajax經典案例開發大全》中該方法的代碼是有誤沒有實現真正的初始化function initSelArray(selA,selB,selC) {selArray[0] = selA;selArray[1] = selB;selArray[2] = selC;}//清除下級子列表選項function clearSubSel(targetId) {var len = selArray.length;for(var i=0;i<len;i++) {var j = 0;if(selArray[i] == targetId) {j = i;break;}}for(; j<len; j++) {clearOptions(document.getElementById(selArray[j]));}//《Ajax經典案例開發大全》中該方法的代碼是有誤,不能實現下級列表全部清除功能,且代碼冗餘,如下示://var canClear = false;//for(var i=0; i<selArray.length; i++) {//if(selArray[i] == targetId) {//canClear = true;//}//if(canClear) {//clearOptions(document.getElementById(selArray[i]));//}//}}</script></head><!-- 頁面載入完畢做2件事:1.初始化列表數組,2.為第一個列表賦值 --><body onload="initSelArray('selA','selB','selC');buildSelect('INIT','selA')"><h1>多級聯動菜單</h1><table><tr><td>列表A</td><td><select name="selA" id="selA" onchange="buildSelect(this.value,'selB')"><option value="" selected>-------請選擇-------</option></select></td></tr><tr><td>列表B</td><td><select name="selB" id="selB" onchange="buildSelect(this.value,'selC')"><option value="" selected>-------請選擇-------</option></select></td></tr><tr><td>列表C</td><td><select name="selC" id="selC"><option value="" selected>-------請選擇-------</option></select></td></tr></table></body></html>


 

        4.select_menu.jsp後台服務

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ page import="java.sql.*,com.lanp.ajax.db.DBUtils" %>    <%!//訪問資料庫取得下級選項資訊String getOptions(String selectedId) {int counter = 0;StringBuffer opts = new StringBuffer("{");String sql = "select * from select_menu where pid=? order by seq asc";Connection conn = null;PreparedStatement pstmt = null;ResultSet rs = null;try {conn = DBUtils.getConnection();pstmt = conn.prepareStatement(sql);pstmt.setString(1,selectedId);rs = pstmt.executeQuery();while(rs.next()) {//如果不是第一項,追加一個","用於分隔選項if(counter > 0) {opts.append(",");}opts.append("'");opts.append(rs.getString("id"));opts.append("':'");opts.append(rs.getString("text"));opts.append("'");counter++;}} catch(SQLException e) {System.out.println(e.toString());} finally {DBUtils.closeResources(conn,pstmt,rs);}opts.append("}");System.out.println(opts.toString());return opts.toString();}%><%out.clear();String selectedId = request.getParameter("selectedId");String optionsInfo = getOptions(selectedId);out.print(optionsInfo);%>


OK,TKS。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.