ajax+js动态创建四级联动菜单

    自己写了一个用AJAX+JS实现自动创建四级联动(国家,省,城市,区县)菜单的例子,效果如下:

代码如下,希望各位高手点评!

数据库oracle,用了四张表:国家这张表在访问JSP时自动从数据库里面加载:

 

create table country(
co_id number primary key,
co_name varchar2(20)not null
);
insert into country values(1,'中国');
insert into country values(2,'日本');
insert into country values(3,'美国');
insert into country values(4,'澳大利');
insert into country values(5,'哥伦比亚');
create table pronvice(
pr_id number primary key,
pr_name varchar2(20)not null,
co_id number not null
);
insert into pronvice values(1,'安徽省',1);
insert into pronvice values(2,'北京市',1);
insert into pronvice values(3,'重庆市',1);
insert into pronvice values(4,'福建省',1);
insert into pronvice values(5,'甘肃省',1);
insert into pronvice values(6,'广东省',1);
insert into pronvice values(7,'广西壮族自治区',1);
insert into pronvice values(8,'贵州省',1);
insert into pronvice values(9,'海南省',1);
insert into pronvice values(10,'河北省',1);
insert into pronvice values(11,'黑龙江省',1);
insert into pronvice values(12,'河南省',1);
insert into pronvice values(13,'香港特别行政区',1);
insert into pronvice values(14,'湖北省',1);
insert into pronvice values(15,'湖南省',1);
insert into pronvice values(16,'江苏省',1);
insert into pronvice values(17,'江西省',1);
insert into pronvice values(18,'吉林省',1);
insert into pronvice values(19,'辽宁省',1);
insert into pronvice values(20,'澳门特别行政区',1);
insert into pronvice values(21,'内蒙古自治区',1);
insert into pronvice values(22,'宁夏回族自治区',1);
insert into pronvice values(23,'青海省',1);
insert into pronvice values(24,'山东省',1);
insert into pronvice values(25,'上海市',1);
insert into pronvice values(26,'陕西省',1);
insert into pronvice values(27,'山西省',1);
insert into pronvice values(28,'四川省',1);
insert into pronvice values(29,'台湾省',1);
insert into pronvice values(30,'天津市',1);
insert into pronvice values(31,'新疆维吾尔自治区',1);
insert into pronvice values(32,'西藏自治区',1);
insert into pronvice values(33,'云南省',1);
insert into pronvice values(34,'浙江省',1);

insert into pronvice values(35,'长崎',2);
insert into pronvice values(36,'广岛',2);
create table city(
ci_id number primary key,
ci_name varchar2(20)not null,
pr_id number not null
);
insert into city values(1,'南坪',3);
insert into city values(2,'观音桥',3);
insert into city values(3,'成都',28);
insert into city values(4,'绵羊',28);
insert into city values(5,'长崎A',35);
insert into city values(6,'长崎B',35);
insert into city values(7,'广岛A',36);
insert into city values(8,'广岛B',36);

create table area(
ar_id number primary key,
ar_name varchar2(20)not null,
ci_id number not null
);
insert into area values(1,'弹子石',1);
insert into area values(2,'洋人街',1);
insert into area values(3,'5公里',1);
insert into area values(4,'小苑',2);
insert into area values(5,'金源',2);
insert into area values(6,'建新',2);
select * from city;
select * from pronvice;
select * from country;

jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <script type="text/javascript" src=\'#\'" /ajax.js" charset="gb2312"></script>
  </head>
 
  <body onload="country()">
  <center>
    <h1>AJAX实现联动菜单</h1>
    <hr/>
    <table align="center">
     <tr>
       <td id="1">
        <select id="country" onchange="getPronvice()" style="text-align: center;">
            <option>---请选择---</option>
        </select>
       </td>
       <td id="2"></td>
       <td id="3"></td>
       <td id="4"></td>
     </tr>
    </table>
    </center>
  </body>
</html>
 

 

JS页面:

 

var xmlHttp;
var zcq=0;
//自动加载国家
function country() {
    var text = "sql=SELECT co_name FROM COUNTRY order by nvl(length(trim(co_name)),0) asc,co_name";
    var url = "ajax/ajax!selectName.action";
    createXmlhttp();
    if (xmlHttp) {
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        xmlHttp.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                parseMessage('country');
            }
        }
        xmlHttp.send(text);
    }
}

//实现一级联动省份
function getPronvice() {
    var country = document.getElementById("country").value;
    var url = "ajax/ajax!selectName.action";
    var text = "sql=SELECT pr_name FROM pronvice pr,country co WHERE co.co_id=pr.co_id and co.co_name='"
            + country + "' order by nvl(length(trim(pr_name)),0) asc,pr_name";
    createXmlhttp();
    if (xmlHttp) {
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        xmlHttp.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if(zcq==0){
                    createSelect('pronvice', '2', 'getCity()');
                    zcq=1;
                }
               
                parseMessage('pronvice');
            }
        }
        xmlHttp.send(text);
    }
}
//实现二级联动城市
function getCity() {
    var pronvice = document.getElementById("pronvice").value;
    var url = "ajax/ajax!selectName.action";
    var text = "sql=SELECT ci_name FROM city ci,pronvice pr WHERE ci.pr_id = pr.pr_id and pr.pr_name='"
            + pronvice + "' order by nvl(length(trim(ci_name)),0) asc,ci_name";
    createXmlhttp();
    if (xmlHttp) {
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        xmlHttp.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if(zcq==1){
                    createSelect('city', '3', 'getArea()');
                    zcq=2;
                }
               
                parseMessage('city');
            }
        }
        xmlHttp.send(text);
    }
}
//实现三级联动区县
function getArea() {
    var city = document.getElementById("city").value;
    var url = "ajax/ajax!selectName.action";
    var text = "sql=SELECT ar_name FROM city ci,area ar WHERE ci.ci_id=ar.ci_id and ci.ci_name='"
            + city + "' order by nvl(length(trim(ar_name)),0) asc,ar_name";
    createXmlhttp();
    if (xmlHttp) {
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        xmlHttp.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if(zcq==2){
                    createSelect('area', '4', '');
                    zcq=3;
                }
               
                parseMessage('area');
            }
        }
        xmlHttp.send(text);
    }
}
//创建xmlHttp对象
function createXmlhttp() {
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
}
//自动创建创建下拉菜单方法
function createSelect(iid, id, methodName) {
    var select = document.createElement("select");
    select.style.cssText = "text-align: center";
    select.id = iid;
    document.getElementById(id).appendChild(select);
    var obj = document.getElementById(iid);
    obj.setAttribute("onchange", methodName);
}
//动态解析生成下拉菜单
function parseMessage(id) {
    var xmlDoc = xmlHttp.responseXML.documentElement;
    var xSel = xmlDoc.getElementsByTagName('root');
    var select_root = document.getElementById(id);
    select_root.options.length = 0;
    for ( var i = 0; i < xSel.length; i++) {
        var xValue = xSel[i].childNodes[0].firstChild.nodeValue;
        var xText = xSel[i].childNodes[0].firstChild.nodeValue;
        var option = new Option(xText, xValue);
        select_root.add(option);
    }
}

 

action页面:

package com.zit.ajaxJoin.action;


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

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.zit.ajaxJoin.dao.AjaxJoinDao;
import com.zit.ajaxJoin.dao.impl.AjaxJoinDaoImpl;

public class AjaxAction extends ActionSupport{
    private static final long serialVersionUID = 1L;
   
    private String sql;

    public String getSql() {
        return sql;
    }
    public void setSql(String sql) {
        this.sql = sql;
    }
    public String selectName() throws IOException{
        HttpServletResponse response= ServletActionContext.getResponse();
        response.setContentType("html/xml;charset=gb2312");
        response.setCharacterEncoding("UTF-8");
        AjaxJoinDao ajax=new AjaxJoinDaoImpl();
        List<String>list=ajax.selectName(sql);
        String strat_xml="<roots>";
        String end_xml="</roots>";
        String xml="<root><name>---请选择---</name></root>";
        for(String string:list){
            xml+="<root><name>"+string+"</name></root>";
        }
        response.getWriter().write(strat_xml+xml+end_xml);
        return null;
    }
}

实现类查询数据库的方法:

package com.zit.ajaxJoin.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.zit.ajaxJoin.dao.AjaxJoinDao;
import com.zit.ajaxJoin.db.Db;

public class AjaxJoinDaoImpl implements AjaxJoinDao {

    private Connection conn;
    private PreparedStatement ps;
    private Statement stmt;
    private ResultSet rs;
    private Db db=null;
    public List<String> selectName(String sql) {
        if(null==db){
            db=new Db();
        }
        //System.out.println(sql);
        List<String>list=new ArrayList<String>();
        try {
            conn=db.getConnection();
            conn.setAutoCommit(false);
            stmt=conn.createStatement();
            rs=stmt.executeQuery(sql);
            conn.commit();
            while(rs.next()){
                list.add(rs.getString(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            db.close(conn, ps, stmt, rs);
        }
        return list;
    }
}
 

struts.xml配置信息:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
    <package name="ajax" namespace="/ajax" extends="struts-default">
      <action name="ajax" class="com.zit.ajaxJoin.action.AjaxAction">
        <result name="success">
          /success.jsp
        </result>
      </action>
    </package>
</struts>
 

本文出自 “成全博客” 博客,谢绝转载!

你可能感兴趣的:(java,Ajax,职场,联动菜单,休闲)