ajax 两级联动下拉列表 和 显示相应数据
实验.Ajax二级联动
Ajax的应用实验目的:通过用EditPlus直接编写带javascript的HTML文件,实现用户名简单验证和二级联动的功能,理解Ajax的基本工作原理,并初步掌握Ajax应用的开发过程。
:实验步骤:一、使用记事本建立一个基本的HTML文件,输入如下代码:保存文件为:html格式:<HTML><HEAD><TITLE> 用户信息</TITLE></HEAD><BODY><form action = "" method = "post" name=”form1”><table border = 3 id = "table1" ><caption><center>用户信息</center></caption><tr> <td>请输入昵称:</td><td> <input type = "text" id = "username" name = "username"></td> </tr> <tr> <td>请输入密码:</td><td><input type = "password" id = "password1" name = "password1"></td> </tr> <tr> <td>请确认密码:</td><td><input type = "password" id = "password2" name = "password2"></td> </tr> <tr> <td> 爱好:</td><td><input type = "checkbox" name = "checkbox1" value = "1" id= "Favirate1"> 足球<input type = "checkbox" name = "checkbox1" value = "2" id= "Favirate2"> 上网<input type = "checkbox" name = "checkbox1" value = "3" id= "Favirate3"> 音乐<input type = "checkbox" name = "checkbox1" value = "4" id= "Favirate4"> 看书</td> </tr><tr> <td>性别:</td><td> <input type = "radio" name = "sex" checked>男<input type = "radio" name = "sex">女</td></tr><tr> <td>所在地区</td><td> <select size = "1" name = "city" tabindex = "5" id = "city"><option selected value = "河北市">河北市</option><option value = "安徽省">安徽省</option></select> </tr><tr> <td colspan="2" align="center"><input type = "submit" id = "reg" value = "提交"><input type = "reset" id = "reset" value = "重置"></td></tr></table></form></BODY></HTML>对其中的昵称的表单值用Ajax方式进行后台校验,要求后台判断用户注册的用户名是否已注册,并返回提示信息。
ajax两级联动下拉列表和显示相应数据
ajax两级联动下拉列表和显示相应数据
本人实现了 ajax 异步实现两级联动的下拉列表和分类显示数据:应该算是充分的实现例子,包含了 JS + CSS 的简单设计
显示:显示书籍大类 ----> 无刷新的显示相对应的书籍小类;
选择书籍小类时候,自动显示相应的书籍信息!
自己试试吧,试试才知道,很好用的
纯手写的实例,仅供学习探究!
Jsp页面:
<%@ page language="java" import="java.util.*,com.AjaxDemo.optionLists.Dao,java.sql.*;"
contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
table{
width: 500px;
text-align: center;
font: bold fantasy 25px;
}
td{
height:35px;
width: 95px;
border-bottom-width:1px;
border-bottom-color: orange;
border-bottom-style: solid;
}
书籍大类:
<%}}catch (SQLException e) {e.printStackTrace();}finally{data.close();} %>
书籍小类:
请选
择
书
籍
类
别
!。
ajax+java+jsp做的二级菜单联动(全)
ajax+java+jsp做的二级菜单联动(全)/*Navicat MySQL Data TransferSource Server : meetingroomMSSource Server Version : 50146Source Host : localhost:3306Source Database : skyTarget Server Type : MYSQLTarget Server Version : 50146File Encoding : 65001*/SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `category`-- ----------------------------DROP TABLE IF EXISTS `category`;CREATE TABLE `category` (`id` int(11) NOT NULL DEFAULT '0',`name` varchar(50) DEFAULT NULL,`level` int(11) DEFAULT NULL,`parentid` int(11) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of category-- ----------------------------INSERT INTO `category` VALUES ('1', '数据库开发', '0', '0'); INSERT INTO `category` VALUES ('2', 'mysql5.0', '1', '0'); INSERT INTO `category` VALUES ('3', 'IBM DB2', '1', '0');INSERT INTO `category` VALUES ('4', 'Orcal', '1', '0'); INSERT INTO `category` VALUES ('5', 'web 开发', '0', '1'); INSERT INTO `category` VALUES ('6', 'asp', '1', '1'); INSERT INTO `category` VALUES ('7', 'jsp', '1', '1'); INSERT INTO `category` VALUES ('8', 'php', '1', '1'); INSERT INTO `category` VALUES ('9', '其他', '0', '2'); INSERT INTO `category` VALUES ('10', 'abc', '1', '2'); INSERT INTO `category` VALUES ('11', 'bbb', '1', '2'); INSERT INTO `category` VALUES ('12', 'ccc', '1', '2');========================本个数据库 Mysql 5.0 ,用户名:root ,密码:123一个类来获得数据库的 getCon()package com.xmlT est.yuan.DB;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class ConnDB {public Connection getCon(){try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}String url = "jdbc:mysql://localhost:3306/sky"; Connection con = null;try {con = DriverManager.getConnection(url,"root","123");} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return con;}}----------------------index.jsp----------------------<%@ page language="java" import="java.util.*,com.xmlTest.yuan.DB.*,java.sql.*" pageEncoding="GBK"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+reque st.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>ajax + java + jsp 做的二级菜单联动 </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"> <!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript"><!--var cache=[];function getLevel2(){// if(document.forms.form1.select1.selectedIndex==0){// document.forms.form1.select2.length=1;// return ;// }//if( !cache[document.forms.form1.selectedIndex]){var xmlhttp;try{xmlhttp=new ActiveXObject('Msxml2.XMLHTTP');}catch(e){try{xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');}catch(e){try{xmlhttp= new XMLHttpRequest();}catch(e){ }}}//alert("document.form1.select1.value="+(document.forms. form1.select1.selectedIndex-1));xmlhttp.onreadystatechange = function(){if(xmlhttp.readystate==4){if(xmlhttp.status==200){var tt =xmlhttp.responseT ext;var ttlength= tt.indexOf(',,');var strtt = tt.slice(0,ttlength);//截取字符串var stArray = strtt.split(',');//把它们放入数组var sltCity = document.forms["form1"].elements["select2"];for(var i=0;i<stArray.length;i++){sltCity[i+1]= new Option(stArray[i+1],stArray[i+1]);}}else{//alert(xmlhttp.status+"=xmlhttp.status-");}}else{// if(xmlhttp.readystate==0){// alert("对象已经建立,没有初始化...");// }// if(xmlhttp.readystate==1){// alert("open 的方法已经调用但尚未调用send 方法");// }// if(xmlhttp.readystate==2){// alert("send 的方法已经调用其他的未知");// }// if(xmlhttp.readystate==3){// alert("请求发送成功");// }// if(xmlhttp.readystate==4){// alert("数据接受成功");// }// alert(xmlhttp.readystate+"xmlhttp.readystate");}}//这个最好放在后面,必须加returnxmlhttp.open("get","ajax.jsp?id="+(document.forms.form1.s elect1.selectedIndex-1) );xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');xmlhttp.send(null);return ;// }}--></script></head><body>This is my JSP page. kao <br><form name="form1" ><select name="select1" onchange="getLevel2()"><option >选择一级分类</option><%ConnDB cdb = new ConnDB();Connection con = cdb.getCon();Statement stmt = null;String sql = "select * from category where level=0";//String parentid = "2";//String sql = "select * from category where parentid="+parentid;ResultSet rs = null;try {stmt = con.createStatement();rs = stmt.executeQuery(sql);while(rs.next()){System.out.println(rs.getInt(4));rs.getInt(4);%><option value="<%=rs.getInt(4) %>"><%=rs.getString(2)%> </option><% }} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {rs.close();stmt.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}%></select><select name="select2" ><option valer="0" >请选择。
PHPAJAX2级联动下拉列表(...
PHPAJAX2级联动下拉列表(...PHP+AJAX2级联动下拉列表(简单好用)这次给大家展示的是非常常用的一个ajax功能--联动下拉列表,本程序采用2级联动,根据数据库的内容用ajax处理下拉列表内容,实现根据用户需求取得下拉选项,交互性强,更新容易。
废话少说,不如正题,这次依然象往常一样提供截图和源码下载,首先还是AJAX框架:var http_request=false;function send_request(url){//初始化,指定处理函数,发送请求的函数http_request=false;//开始初始化XMLHttpRequest对象if(window.XMLHttpRequest){//Mozilla浏览器http_request=new XMLHttpRequest();if(http_request.overrideMimeType){//设置MIME类别http_request.overrideMimeType("text/xml");}}else if(window.ActiveXObject){//IE浏览器try{http_request=new ActiveXObject("Msxml2.XMLHttp");}catch(e){try{http_request=new ActiveXobject("Microsoft.XMLHttp");}catch(e){}}}if(!http_request){//异常,创建对象实例失败window.alert("创建XMLHttp对象失败!");return false;}http_request.onreadystatechange=processrequest;//确定发送请求方式,URL,及是否同步执行下段代码http_request.open("GET",url,true);http_request.send(null);}//处理返回信息的函数function processrequest(){if(http_request.readyState==4){//判断对象状态if(http_request.status==200){//信息已成功返回,开始处理信息document.getElementById(reobj).innerHTML=http_request.respons eText;}else{//页面不正常alert("您所请求的页面不正常!");}}}function getclass(obj){var pid=document.form1.select1.value;document.getElementById(obj).innerHTML="<option>loading...</o ption>";send_request(‘doclass.php?pid=‘+pid);reobj=obj;}这个程序的核心就是动态添加<option>......</option>服务器端是进行数据的检索,很简单:<?phpheader("Content-type: text/html;charset=GBK");//输出编码,避免中文乱码$pid=$_GET[‘pid‘];$db=mysql_connect("localhost","root","7529639"); //创建数据库连接mysql_query("set names ‘GBK‘");mysql_select_db("menuclass");$sql="select classname from menu where parentid=".$pid."";$result=mysql_query($sql);//循环列出选项while($rows=mysql_fetch_array($result)){echo ‘<option>‘;echo $rows[‘classname‘];echo "</option>\n";}>再看看列表页面的html:<script language="javascript" src="ajaxmenu.js"></script><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>ajax2级联动菜单演示</title></head><body><form name="form1"><select name="select1" id="class1" style="width:100;" onChange="getclass(‘class2‘);"><option selected="selected"></option><option value="1">大类1</option><option value="2">大类2</option></select><select name="select2"id="class2" style="width:100;"></select></form></body></html>附件1.jpg(1.99 KB)2007-9-24 10:04PHP+AJAX2级联动下拉列表2.jpg(3.25 KB)2007-9-24 10:04PHP+AJAX2级联动下拉列表3.jpg(5.92 KB)2007-9-24 10:04PHP+AJAX2级联动下拉列表4.jpg(5.62 KB)2007-9-24 10:04PHP+AJAX2级联动下拉列表ajaxdemo.rar(1.66 KB)2007-9-24 10:05, 下载次数: 3PHP+AJAX2级联动下拉列表搜索更多相关主题的帖子: AJAX PHP列表台州南开技术小组专门用PHP+MYSQL技术进行Web(网站、平台、系统等)开发,凭借其开发产品的非凡速度、领先的技术优势、富于创新的开发团队,为众多行业门户、专业型站点提供最有优质的服务和技术保障。
Ajax选中一个列表的值另一个列表的值根据他也得到相应的值
AJAX,,通过一个下拉列表的选中的值,另一个下来列表所有的值都根据第一个下拉列表的的值显示出来-------------------------------------伊剑/**根据学院查询专业(在action里,orcl数据库,jsp UTF-8编码,tomcat 配UTF-8)*/public String getListZhuanyeAjax(){StringBuffer responseText = new StringBuffer();StringdeptNameXueYuan=ServletActionContext.getRequest().getParameter("deptNameXueYuan");if("--请选择--".equals(deptNameXueYuan.replaceAll(" ",""))){responseText.append("no");}else{String num=dormIformationService.getdeptNum(deptNameXueYuan.replaceAll(" ",""));List<?> zhuanye=dormIformationService.getListZhuanye(num);if (zhuanye!=null){for (int i = 0; i < zhuanye.size(); i++) {responseText.append(zhuanye.get(i)+",");}}}HttpServletResponse response=ServletActionContext.getResponse();response.setCharacterEncoding("utf-8");response.setContentType("text/plain");response.setHeader("Cache-Control", "no-store"); //HTTP1.1response.setHeader("Pragma", "no-cache"); //HTTP1.0response.setDateHeader("Expires", 0);try {response.getWriter().write(responseText.toString().trim());} catch (IOException e) {e.printStackTrace();}return null;}-------------------------------------------------------------(在jsp的javascript里的方法)//获取专业var req;function getZhuanye() {var deptNameXueYuan= document.form1.deptNameXueYuan.value;if(window.XMLHttpRequest) {req = new XMLHttpRequest();} else if (window.ActiveXObject) {req = new ActiveXObject("Microsoft.XMLHTTP");}req.open("POST","<%=basePath%>dormIformationAction!getListZhuanyeAjax",true);req.onreadystatechange = callbackzhuanye;req.setRequestHeader("Content-type","application/x-www-form-urlencoded");req.send("deptNameXueYuan="+deptNameXueYuan+" ");//post方式发动的话要在这写入参数}function callbackzhuanye() {if (req.readyState == 4) {if (req.status == 200) {parsezhuanye(req.responseText); //使用解析文本方法}}}//解析文本function parsezhuanye(msg) {msg = msg.replace(/(^\s*)|(\s$)/g, "");var msgs = new String(msg);if (msgs == null || msgs == "") {document.form1.zhuanye.length = 1;document.form1.zhuanye.selectedIndex = 0;document.form1.zhuanye.options[0].text = "--请选择--";document.form1.zhuanye.options[0].value = "--请选择--";return false;}var categories = msg.split(",");document.form1.zhuanye.length = categories.length;document.form1.zhuanye.selectedIndex = 0;document.form1.zhuanye.options[0].text = "--请选择--";document.form1.zhuanye.options[0].value = "--请选择--";for ( var i = 0; i < categories.length; i++) {var categoryprops = categories[i].split(",");var id = categoryprops[0];var name = categoryprops[0];document.form1.zhuanye.options[i+1].text = name;document.form1.zhuanye.options[i+1].value = id;}}---------------------------------(jsp里的下拉列表)<td width="12%"> 学院:</td><td width="27%"><select name="deptNameXueYuan" id="deptNameXueYuan" onchange="getZhuanye()"><option selected="selected" value="--请选择--">--请选择--</option><c:forEach items="${xueY uanList}" var="xueYuanList"><option value="${xueYuanList.deptName}" <c:if test="${xueYuanList.deptName==deptNameXueYuan}"><c:outvalue="selected"/></c:if> >${xueYuanList.deptName}</option></c:forEach></select></td><td width="12%"> 专业:</td><td width="48%"><select name="zhuanye" id="zhuanye"><option selected="selected" value="--请选择--">--请选择--</option><c:if test="${!empty zhuanye}"><option value="${zhuanye}" selected="selected" >${zhuanye}</option></c:if></select></td>。
java AJAX实现级联下拉框
new
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE class SYSTEM "product.dtd" > <class> <class1 className="电脑配件" id="1"> <class2 className="内存" id="1"> <class3 id="1" className="kingmax"></class3> <class3 id="2" className="kingston"></class3> <class3 id="3" className="samsung"></class3> <class3 id="4" className="hydadi"></class3> <class3 id="5" className="ibm"></class3> </class2> <class2 className="硬盘" id="2"> <class3 id="6" className="hithait"></class3> <class3 id="7" className="IBM"></class3> <class3 id="8" className="samsung"></class3> <class3 id="9" className="westdata"></class3> </class2> </class1> <class1 className="食品配件" id="2"> <class2 className="汉堡包" id="1"> <class3 id="1" className="麦当劳"></class3> <class3 id="2" className="肯得基"></class3> <class3 id="3" className="罗杰丝"></claቤተ መጻሕፍቲ ባይዱs3>
级联菜单、连库查询(ajax)
if(xmlHttp.status==200 || xmlHttp.status==0)
function BuildSel(str,sel)
{
//先清空原来的数据.
sel.options.length=0;
//定义一个数组对象
var substr= new Array();
substr = str.split(",");
<fieldset style="padding-left: 10%">
<legend>
区域查询:
</legend>
<label><select name="sheng" id="sheng" >
<option value="河北省">河北省</option>
<%}
%>
</select>县</label>
<label> <select name="xiang" id="xiang" onchange="changexiang(this.value)">
//subarrstr=substr[i].split("|");
sel.options.add(new Option(substr[i],substr[i]));
Ajax二级联动简单实例
Ajax⼆级联动简单实例效果图:图1图2(浙江省内存在⼭东省的数据,原因是先前加⼊的数据未删除)思路:通过下拉省份,将省份id传⼊后台,根据省份塞⼊相应省份的市的数据,将市的数据再次传回前端前端HTML及JS代码:<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript">function loadInfo(){var shengId=document.getElementById("sheng").value;shi.options.length=0; // 页⾯加载前先删除所有市下拉框的选项,避免原先加⼊的市同时存在,即避免图⼆的情况出现var xmlHttp;if(window.XMLHttpRequest){xmlHttp=new XMLHttpRequest();}else{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==4 && xmlHttp.status==200){alert(xmlHttp.responseText);var dataObj=eval("("+xmlHttp.responseText+")");for(var i=0;i<dataObj.rows.length;i++){var o=dataObj.rows[i];shi.options.add(new Option(o.text,o.id));}}};xmlHttp.open("get", "getAjaxInfo?action=ejld&shengId="+shengId, true);xmlHttp.send();}</script></head><body>省:<select id="sheng" onchange="loadInfo()"><option value="1">江苏省</option><option value="2">⼭东省</option><option value="3">浙江省</option></select> 市<select id="shi"></select></body></html>后台servlet代码:public class GetAjaxInfoServlet extends HttpServlet{/****/private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");String action=request.getParameter("action");if("checkUserName".equals(action)){this.checkUserName(request, response);}else if("ejld".equals(action)){this.ejld(request, response);}}private void checkUserName(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {PrintWriter out=response.getWriter();String userName=request.getParameter("userName");JSONObject resultJson=new JSONObject();if("jack".equals(userName)){resultJson.put("exist", true);}else{resultJson.put("exist", false);}out.println(resultJson);out.flush();out.close();}private void ejld(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {PrintWriter out=response.getWriter();String shengId=request.getParameter("shengId");JSONObject resultJson=new JSONObject();JSONArray jsonArray=new JSONArray();JSONObject temp=null;//以下为根据省ID模拟该省的市的数据switch(Integer.parseInt(shengId)){case 1:{temp=new JSONObject();temp.put("id", 1);temp.put("text", "南京");jsonArray.add(temp); temp=new JSONObject();temp.put("id", 2);temp.put("text", "南通");jsonArray.add(temp); temp=new JSONObject();temp.put("id", 3);temp.put("text", "泰兴");jsonArray.add(temp); break;}case 2:{temp=new JSONObject();temp.put("id", 4);temp.put("text", "济南");jsonArray.add(temp); temp=new JSONObject();temp.put("id", 5);temp.put("text", "烟台");jsonArray.add(temp); temp=new JSONObject();temp.put("id", 6);temp.put("text", "蓬莱");jsonArray.add(temp); break;}case 3:{temp=new JSONObject();temp.put("id", 7);temp.put("text", "杭州");jsonArray.add(temp); temp=new JSONObject();temp.put("id", 8);temp.put("text", "宁波");jsonArray.add(temp); temp=new JSONObject();temp.put("id", 9);temp.put("text", "温州");jsonArray.add(temp); break;}}resultJson.put("rows", jsonArray);out.println(resultJson);out.flush();out.close();}}Servlet在web.xml中的配置:<servlet><servlet-name>getAjaxInfoServlet</servlet-name><servlet-class>com.XXXXX.web.GetAjaxInfoServlet</servlet-class></servlet><servlet-mapping><servlet-name>getAjaxInfoServlet</servlet-name><url-pattern>/getAjaxInfo</url-pattern></servlet-mapping>。
vue实现下拉框二级联动效果的实例代码
vue实现下拉框⼆级联动效果的实例代码1、实现效果2、后端返回的数据格式"list": [{"id": "1178214681118568449","title": "后端开发","children": [{"id": "1178214681139539969","title": "Java"},{"id": "1178585108407984130","title": "Python"},{"id": "1454645056483913730","title": "C++"},{"id": "1454645056731377666","title": "C#"}]},{"id": "1178214681181483010","title": "前端开发","children": [{"id": "1178214681210843137","title": "JavaScript"},{"id": "1178585108454121473","title": "HTML/CSS"}]},{"id": "1178214681231814658","title": "云计算","children": [{"id": "1178214681252786178","title": "Docker"},{"id": "1178214681294729217","title": "Linux"}]},{"id": "1178214681324089345","title": "系统/运维","children": [{"id": "1178214681353449473","title": "Linux"},{"id": "1178214681382809602","title": "Windows"}]},{"id": "1178214681399586817","title": "数据库","children": [{"id": "1178214681428946945","title": "MySQL"},{"id": "1178214681454112770","title": "MongoDB"}]},{"id": "1178214681483472898","title": "⼤数据","children": [{"id": "1178214681504444418","title": "Hadoop"},{"id": "1178214681529610242","title": "Spark"}]},{"id": "1178214681554776066","title": "⼈⼯智能","children": [{"id": "1178214681584136193","title": "Python"}]},{"id": "1178214681613496321","title": "编程语⾔","children": [{"id": "1178214681626079234","title": "Java"}]}]数据格式不⼀定和上⾯的⼀样,我上⼀篇⽂章是把这个数据格式⽤在了树形控件上⾯,这⾥放在⼆级联动上⾯。
使用Ajax和Jquery配合数据库实现下拉框的二级联动的示例
使⽤Ajax和Jquery配合数据库实现下拉框的⼆级联动的⽰例⾸先我们需要先建⽴好数据库,将⼀些数据插⼊进去需要两张表:province:省份表city:城市表如图:然后再在java中建⽴相关的实体类与之对应再然后,我们就能开始做jdbc的操作了public class ConnectionFactory {private static String driver;private static String url;private static String user;private static String password;static {Properties prop = new Properties();//读取⽂件try {InputStream in = ConnectionFactory.class.getResourceAsStream("./jdbc.properties");prop.load(in);driver = prop.getProperty("jdbc.driver");url = prop.getProperty("jdbc.url");user = prop.getProperty("er");password = prop.getProperty("jdbc.password");} catch (IOException e) {e.printStackTrace();}}/*** 获取连接对象* @returnpublic static Connection getConnection(){Connection conn = null;try {Class.forName(driver);conn = DriverManager.getConnection(url, user, password);} catch (Exception e) {throw new RuntimeException(e);}return conn;}/*** 关闭资源* @param conn* @param pstmt* @param stmt* @param rs*/public static void close(Connection conn,PreparedStatement pstmt,Statement stmt,ResultSet rs){ try {if (conn != null) {conn.close();}if (pstmt != null) {pstmt.close();}if (stmt != null) {stmt.close();}if (rs != null) {rs.close();}} catch (SQLException e) {throw new RuntimeException(e);}}⾸先我们可以在页⾯加载的时候获取所有省份的信息,SQL语句如下Connection conn = null;PreparedStatement pstmt = null;Province province2 = null;@Overridepublic ArrayList<Province> findAllPro() {ResultSet rs = null;ArrayList<Province> pros = null;try {String sql = "select id,place from province";conn = ConnectionFactory.getConnection();pstmt = conn.prepareStatement(sql);pros = new ArrayList<Province>();rs = pstmt.executeQuery();while(rs.next()){Province province = new Province();province.setId(rs.getInt(1));province.setPlace(rs.getString(2));pros.add(province);}} catch (SQLException e) {throw new RuntimeException(e);}return pros;将查到的数据放到后台,建⽴⼀个SelectedServlet类,⽤于接收查询到的所有省份的信息response.setContentType("application/json;charset=utf-8");response.setCharacterEncoding("utf-8");request.setCharacterEncoding("utf-8");//创建⼀个Place对象ArrayList<Province> pros= new Place().findAllPro();PrintWriter out = response.getWriter();//将集合直接转换为Json对象out.write(JSONArray.fromObject(pros).toString());在这⾥会⽤到集合转换Json对象,我们需要导⼊以下⼏个包然后我们开始写前台页⾯:<body>省份:<select id="province"><option>--请选择省份--</option></select>城市:<select id="city"><option>--请选择城市--</option></select><br/><br/><span></span></body>然后jQuery代码如下:(由于我导⼊的jQuery版本⽐较低,所以使⽤的⽅法是getJSON,⽽不是getJson)$.getJSON("SelectedServlet",function(data,textStatus){var provinces = data;var res = "";for(var i =0;i<provinces.length;i++){<span style="white-space:pre"> </span>res += "<option>"+provinces[i].place+"</option>";}$("#province").append(res);});这样就能在页⾯加载的时候获取到数据然后我们再来做联动,⾸先给下拉框添加⼀个change事件,然后获取选中的信息,将选中的信息发送到另⼀个CityServlet中//下拉框改变时触发的事件$("#province").change(function(){var seled = $("option:selected").html();$("span").html(seled);$.getJSON("CityServlet",{"province":encodeURI(encodeURI(seled))},function(data){$("#city").html("");var citys = data;var res = "";for(var i = 0;i<citys.length;i++){res += "<option>"+citys[i].place+"</option>";}$("#city").append(res);});});服务器通过获得的信息通过sql语句查询出来,SQL代码如下:public ArrayList<City> findAllCityByPro(String name) {ResultSet rs = null;ArrayList<City> citys = null;try {//通过名字获得所有值String sql = "select c.city_place from city c ,"+ "province p where c.province_id = "+ " (select id from province where place = '"+ name +"') "+ " and c.province_id = p.id";conn = ConnectionFactory.getConnection();pstmt = conn.prepareStatement(sql);citys = new ArrayList<City>();System.out.println(sql);rs = pstmt.executeQuery();while(rs.next()){City city = new City();city.setPlace(rs.getString(1));citys.add(city);}System.out.println(citys);} catch (SQLException e) {e.printStackTrace();}return citys;}将查询到的数据发送到后台,后台接收到数据后将其转换为Json对象,并通过回调函数发送到前台,然后前台就可以通过事件直接获取到数据,⽽不⽤各种跳转页⾯,这就是Ajax(Asynchronous Javascript And XML),protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("application/json;charset=utf-8");response.setCharacterEncoding("utf-8");request.setCharacterEncoding("utf-8");// String proName = "浙江";String proName = URLDecoder.decode(URLDecoder.decode(request.getParameter("province"), "utf-8"),"utf-8");ArrayList<City> citys= new Place().findAllCityByPro(proName);PrintWriter out = response.getWriter();out.write(JSONArray.fromObject(citys).toString());}⾄于显⽰页⾯的代码也在前⾯写到jQuery语句中了效果如下:以上这篇使⽤Ajax和Jquery配合数据库实现下拉框的⼆级联动的⽰例就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
JS+AJAX实现省市区的下拉列表联动
JS+AJAX实现省市区的下拉列表联动本⽂实例为⼤家分享了JS+AJAX实现省市区下拉列表联动的具体代码,供⼤家参考,具体内容如下效果图如下,DB中存取的数据来抽取.前台JSP页⾯的实现<div class="info"><div class="title">企业地址:</div><div class="value"><fieldset disabled><select id="provinceSelect" class="form-control" data-val="${factoryCenterInfo.province}" οnchange="provinceChange()"><c:forEach items="${factoryPlace.provinceList}" var="province" varStatus="status"><option value="${province.key}" <span style="color:#3333ff;"><c:if test="${factoryCenterInfo.province == province.key}">selected</c:if></span><span style="color:#3366ff;">></span>${province.value}</option> </c:forEach></select></fieldset><fieldset disabled><select id="citySelect" class="form-control" data-val="${factoryCenterInfo.city}" οnchange="cityChange()"><c:forEach items="${factoryPlace.cityList}" var="city" varStatus="status"><option value="${city.key}" <span style="color:#3333ff;"><c:if test="${factoryCenterInfo.city == city.key}">selected</c:if></span>>${city.value}</option></c:forEach></select></fieldset><fieldset disabled><select id="areaSelect" class="form-control" data-val="${factoryCenterInfo.area}"><c:forEach items="${factoryPlace.areaList}" var="area" varStatus="status"><option value="${area.key}" <span style="color:#3333ff;"><c:if test="${factoryCenterInfo.area == area.key}">selected</c:if></span>>${area.value}</option></c:forEach></select></fieldset></div></div>JS实现代码效果:实现多次ajax请求,联动搜索数据function provinceChange(){var provinceId = $("#provinceSelect").val();$("#citySelect").empty();$("#areaSelect").empty();if(provinceId != null && provinceId != ""){$.ajax({type: "POST",url:"<span style="color:#3333ff;">factory/getChangeList</span>",dataType:'json',data: {"parentId":provinceId,"placeKbn":"C"},cache:false,success: function(data){if("success" == data.result){if(data.cityList != null && data.cityList.length > 0){for(var i = 0;i < data.cityList.length;i++){var city = data.cityList[i];var key = (city.key == null? "":city.key);var value = (city.value == null? "":city.value);$("#citySelect").append("<option value = \"" + key + "\">"+ value +"</option>");}}else{$("#citySelect").append("<option> </option>");}$("#areaSelect").append("<option> </option>");}if("error" == data.result){$("#citySelect").append("<option> </option>");$("#areaSelect").append("<option> </option>");}},error:function(XMLHttpRequest, textStatus, errorThrown){$("#errorContent").html("系统异常请联系管理员");}});}else{$("#citySelect").append("<option> </option>");$("#areaSelect").append("<option> </option>");}}function cityChange(){var cityId = $("#citySelect").val();$("#areaSelect").empty();if(cityId != null && cityId != ""){$.ajax({type: "POST",url:"<span style="color:#3333ff;">factory/getChangeList</span>",dataType:'json',data: {"parentId":cityId,"placeKbn":"Q"},cache:false,success: function(data){if("success" == data.result){if(data.areaList != null && data.areaList.length > 0){for(var i = 0;i < data.areaList.length;i++){var area = data.areaList[i];var key = (area.key == null? "":area.key);var value = (area.value == null? "":area.value);$("#areaSelect").append("<option value = \"" + key + "\">"+ value +"</option>");}}else{$("#areaSelect").append("<option> </option>");}}if("error" == data.result){$("#areaSelect").append("<option> </option>");}},error:function(XMLHttpRequest, textStatus, errorThrown){$("#errorContent").html("系统异常请联系管理员");}});}else{$("#citySelect").append("<option> </option>");$("#areaSelect").append("<option> </option>");}}后台controller实现代码@RequestMapping("<span style="color:#3333ff;">getChangeList</span>")@ResponseBodypublic Object getChangeList(String parentId,String placeKbn){logBefore(logger, "factory/getChangeList");Map<String,Object> returnMap = new HashMap<String,Object>();if(FactoryConsts.CHAR_KBN_CITY.equals(placeKbn)){if(getPlacelist( parentId, placeKbn) != null && getPlacelist( parentId, placeKbn).size() > FactoryConsts.INT_0){ returnMap.put("result", "success");returnMap.put("cityList", getPlacelist(parentId, placeKbn));}else{returnMap.put("error", "市列表为空");returnMap.put("cityList", "");}}else if(FactoryConsts.CHAR_KBN_AREA.equals(placeKbn)){if(getPlacelist( parentId, placeKbn) != null && getPlacelist( parentId, placeKbn).size() > FactoryConsts.INT_0){ returnMap.put("result", "success");returnMap.put("areaList", getPlacelist(parentId, placeKbn));}else{returnMap.put("error", "区列表为空");returnMap.put("areaList", "");}}return returnMap;}/*** 省下拉列表** @return*/private List<PlaceOption> getPlacelist(String parentId,String kbn){//下拉列表List<PlaceOption> placeList = new ArrayList<PlaceOption>();placeList.add(new PlaceOption());QueryPlaceInfoParam queryParam = new QueryPlaceInfoParam();queryParam.setPlaceKbn(kbn);if(!StringUtils.isEmpty(parentId)){queryParam.setPlaceId(Integer.valueOf(parentId));}FactoryPlaceNameResult placeResult = placeInfoService.queryPlaceInfo(queryParam);if(placeResult != null && "0".equals(placeResult.getResult())&& placeResult.getPlaceInfo() != null&& placeResult.getPlaceInfo().size() > FactoryConsts.INT_0){List<PlaceInfoFa> placeInfo = new ArrayList<PlaceInfoFa>();placeInfo = placeResult.getPlaceInfo();for(FactoryPlaceInfo info : placeInfo){PlaceOption option = new PlaceOption();option.setKey(String.valueOf(info.getPlaceId()));option.setValue(info.getPlaceName());placeList.add(option);}}return placeList;}同时点画⾯menu的时候,画⾯初期话的时候controller实现/*** 基本信息初期化⽅法** @param request* @return*/@RequestMapping("toFactoryBaseInfo")public ModelAndView toFactoryBaseInfo(HttpServletRequest request){logBefore(logger, "factory/toFactoryBaseInfo");ModelAndView mv = new ModelAndView();//企业类型Map<String,String> factoryTypeMap = new TreeMap<String,String>();factoryTypeMap.putAll(FactoryConsts.FACTORY_TYPE_MAP);mv.addObject("factoryTypeMap", factoryTypeMap);FactoryFactoryInfo factoryInfo = (FactoryFactoryInfo) request.getSession().getAttribute(Const.SESSION_FACTORY);//取得企业信息FactoryFactoryInfoParam infoParam = new FactoryFactoryInfoParam();FactoryFactoryInfoResult infoResult = new FactoryFactoryInfoResult();infoParam.setFactoryId(String.valueOf(factoryInfo.getFactoryId()));infoParam.setDifferent(FactoryConsts.STRING_WEB_ONE); //webinfoResult = factoryService.factoryInfo(infoParam);FactoryPlace factoryPlace = new FactoryPlace();<span style="color:#3333ff;">// 省下拉列表factoryPlace.setProvinceList(getPlacelist("0",FactoryConsts.CHAR_KBN_PROVINCE));// 市下拉列表factoryPlace.setCityList(getPlacelist(infoResult.getFactoryInfoEx().getProvince(),FactoryConsts.CHAR_KBN_CITY));// 区下拉列表factoryPlace.setAreaList(getPlacelist(infoResult.getFactoryInfoEx().getCity(),FactoryConsts.CHAR_KBN_AREA));</span> <span style="color:#cc66cc;">mv.addObject("factoryPlace", factoryPlace);//地址的列表</span><span style="color:#6633ff;">mv.addObject("factoryCenterInfo", infoResult.getFactoryInfoEx());//企业表的基本信息</span> mv.setViewName("factory/factoryInformationCenter/saveFactoryBaseInfo");return mv;}多级联动效果就能实现了。
ajax实现下拉框与表格中的单选按钮联动,数据从数据库中查出
ajax实现下拉框与表格中的单选按钮联动,数据从数据库中查出js:$(function() {$('#userType').change(function() {var userType = $(this).val();$("input[type=radio]").attr("checked", false);ajaxForAccessTypeChanged(userType, false);});var userType = $('#userType').val();ajaxForAccessTypeChanged(userType, false); //当下拉框的值改变时,调⽤下⾯的⽅法});function ajaxForAccessTypeChanged(userType) {$.ajax({url : 'a_usr_s01_SelectedUserTypeAjaxBL.do',type : 'post',data : {'userType' : userType},success : function(data, textStatus) {if (data == null || data == "")return;var dataObj = eval("(" + data + ")");$.each(erTypeAccess, function(idx, item) {if (item == null || item == "")return;$("#function_" + item.function_code + " input[value=" + item.accessType + "]").attr("checked", true);});},error : function(XMLHttpRequest, textStatus, errorThrown) {alert("An error has occurred: " + textStatus);}});}jsp:<logic:iterate id="listFunction" name="listFunction" scope="request"><tr id="function_<bean:write name="listFunction" property="idFunction"/>"><td class="tdLeft"><bean:write name="listFunction" property="moduleName" /><html:hidden name="listFunction" property="idModule" indexed="true" /></td><td class="tdLeft"><bean:write name="listFunction" property="functionName" /><html:hidden name="listFunction" property="idFunction" indexed="true" /></td><td class="colAccessType"><html:radio styleId="radio" name="listFunction" property="accessType" indexed="true" value="F" /></td><td class="colAccessType"><html:radio styleId="radio" name="listFunction" property="accessType" indexed="true" value="V" /></td><td class="colAccessType"><html:radio styleId="radio" name="listFunction" property="accessType" indexed="true" value="X" /></td></tr></logic:iterate>BLogic:/*** @(#)A_USR_S01_SelectedUserTypeAjaxAction.java** HMSB Online Service Booking System** Version 1.00** Created 2012-11-16** Copyright (c) 2012 Honda Malaysia. All rights reserved.*/package .honda.servicebooking.a_usr.action;import java.io.PrintWriter;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import .honda.servicebooking.a_usr.dto.A_USR_S01_UserTypeAccess;import jp.terasoluna.fw.dao.QueryDAO;import jp.terasoluna.fw.service.thin.BLogicResult;import jp.terasoluna.fw.web.struts.actions.AbstractBLogicAction;/*** @author i-fannch**/public class A_USR_S01_SelectedUserTypeAjaxAction<P>extends AbstractBLogicAction<P> {private QueryDAO queryDAO;/* (non-Javadoc)* @see jp.terasoluna.fw.web.struts.actions.AbstractBLogicAction#doExecuteBLogic(ng.Object)*/public BLogicResult doExecuteBLogic(P arg0) throws Exception {BLogicResult res = new BLogicResult();return res;}protected void postDoExecuteBLogic(HttpServletRequest request,HttpServletResponse response, P params, BLogicResult result)throws Exception {String userType = request.getParameter("userType");if(userType==null||userType.trim().length()<=0)return;List<A_USR_S01_UserTypeAccess> list = queryDAO.executeForObjectList("SELECT.A_USR.GET_LIST_ACCESSTYPE", userType);if(list!=null&&list.size()>0) {PrintWriter out = response.getWriter();String json="{userTypeAccess: [";for(A_USR_S01_UserTypeAccess ut : list)json += "{function_code: '"+ ut.getIdFunction() +"', accessType: '"+ ut.getAccessType() +"'},";json.substring(0, json.length()-1);json += "]}";out.print(json);out.close();}}public QueryDAO getQueryDAO() {return queryDAO;public void setQueryDAO(QueryDAO queryDAO) { this.queryDAO = queryDAO;}}。
Domino下拉框的二级联动菜单
下拉框的二级联动菜单首先有两个联动菜单,如下图:我们现在要根据SampleType的值来改变SampleName的值。
我们先看一下视图的结构我们通过ajax从后台获取xml,然后放到SampleName里面:当SampleType的值改变时我们调用addSampleNamebyajax方法:Javascript://通过ajax动态加载样品名称function addSampleNamebyajax(samplevalue){try{var uri = "";uri = "&SampleType=" + samplevalue + "&ids=" + Math.random();var loader = dhtmlxAjax.getSync("<计算的值>Agent_getSapmleNameByAjax?OpenAgent" + uri);cResponseSampleName(loader);}catch(err){alert(err.description);}}//回调函数function cResponseSampleName(loader){try{if( != null){//清除数据document.getElementById("SampleName").options.length = 1;//获取ajax的xml数据var xmlDoc = loadXMLDoc(;var temp = xmlDoc.getElementsByTagName("cell");for(i=0;i<temp.length;i++){tempStr = temp[i].childNodes[0].nodeValueoption = new Option(tempStr,tempStr)document.getElementById("SampleName").add(option);}}}catch(err){alert(err.description)}}function loadXMLDoc(dname){try{xmlDoc=new ActiveXObject("Microsoft.XMLDOM");}catch(e){try{xmlDoc="","",null);}catch(e){alert(e.message)}}try {xmlDoc.async=false;xmlDoc.load(dname);return(xmlDoc);}catch(e) {alert(e.message)}return(null);}L OTUSSCRIPT:S UB I NITIALIZE'M SGBOX "-----------------------"O N E RROR G OTO HANDLED IM SESSION A S N EW N OTES S ESSIOND IM CURDOC A S N OTES D OCUMENTD IM INPUT S TR A S S TRINGD IM VIEW A S N OTES V IEWD IM CURDB A S N OTES D ATABASED IM TEMPDOC A S N OTES D OCUMENTD IM DC A S N OTES D OCUMENT C OLLECTIOND IM S AMPLE N AME A S S TRINGD IM OUPUT S TR A S S TRINGS ET CURDB = SESSION.C URRENT D ATABASES ET CURDOC = SESSION.D OCUMENT C ONTEXT'INPUT S TR = CURDOC.G ET I TEM V ALUE("Q UERY_S TRING_D ECODED")(0)INPUT S TR = G ET P ARAMETER("S AMPLE T YPE",CURDOC.G ET I TEM V ALUE("Q UERY_S TRING_D ECODED")(0))'M SGBOX INPUT S TRS ET VIEW = CURDB.G ET V IEW("V IEW_ZNNYSC_S AMPLE T YPE")S ET DC = VIEW.G ET A LL D OCUMENTS B Y K EY(INPUT S TR +"|"+ INPUT S TR,T RUE)M SGBOX DC.C OUNTS ET TEMPDOC = DC.G ET F IRST D OCUMENTOUTPUT S TR ={<ROW>}W HILE N OT TEMPDOC I S N OTHINGS AMPLE N AME = TEMPDOC.S AMPLE T YPE N AME(0)OUTPUT S TR = OUTPUT S TR +{<CELL>}+S AMPLE N AME +{</CELL>}M SGBOX S AMPLE N AMES ET TEMPDOC = DC.G ET N EXT D OCUMENT(TEMPDOC)W ENDOUTPUT S TR = OUTPUT S TR +{</ROW>}P RINT {C ONTENT-T YPE:TEXT/XML;CHARSET=UTF-8}P RINT OUTPUT S TRE XIT S UBHANDLE:M SGBOX E RL &E RROR$E XIT S UBE ND S UB最后:我们需要在SampleName的公式中加上页面打开时获取的值:这样就完成下拉框二级联动了。
Jquery中Ajax实现下拉列表联动
Jquery中Ajax实现下拉列表联动(转载)【Js代码如下】:<script src="Js/jquery-1.2.6.js"type="text/javascript"></script><script language="javascript" type="text/javascript">$(function() {BindUnit();Change();});//下拉列表change事件function Change() {$("#sel_unit").change(function() {BindUnit_User();});}functionBindUnit() {$.ajax({type: "POST",contentType: "application/json",url: "WebService.asmx/GetUnitDS",data: "{}", //即使参数为空,也需要设置dataType: 'xml', //返回的类型为XMLsuccess: function(result) { //成功时执行的方法//捕获处理过程中的异常并输出try {$("#sel_unit").empty();$(result).find("Table").each(function(i) { $("#sel_unit").append(" <option value='" +$(this).find("org_id").text() + "'>" +$(this).find("org_name").text() + "</option>"); });BindUnit_User();}catch (e) {alert(e);return;}}, error: function(result, status) { //出错时会执行这里的回调函数if (status == 'error') { alert(status); }}});}functionBindUnit_User() {varval = $("#sel_unitoption:selected").val();varmydata = '{"org_id":"'+val+'"}': //格式为json的参数,这中间最麻烦,最容易出错的也是拼接Json字符串,字符型参数的值要添加引号,而且对于用户输入的文本字段要对',/等进行特殊处理//varmydata = {"org_id":val}:这种方式是错误的,会报“无效的JS 基元”之类的错误。
ajax获取json格式二级联动下拉菜单
ajax获取json格式⼆级联动下拉菜单在后台交互获得的数据json数据,在前台交互得不到他的值。
,原来要⽤eval()对json数据进⾏转换成对象!!再⽤$.each()函数进⾏循环输出。
1.在1.php中关键代码<div><select name='s' id='ss' onchange="return show(this.value)"><option value="default">请选择</option><?php foreach($arr as $v){?><option value="<?=$v['id']?>"><?=$v['title']?></option><?php }?></select><select name="g" id="gg"><option value="default">--default--</option><option value="v1">t1</option><option value="v2">t2</option><option value="v3">t3</option></select></div>javascript代码为:function show(n){var id = n;$.ajax({type:'GET',url:'2.php',data:'id='+id,success:function(data){var gg = $("#gg");gg.empty(); //每次清空选项。
跟我学AJAX技术——如何应用AJAX技术实现级联菜单的Web应用示例
1.1跟我学AJAX技术——如何应用AJAX技术实现级联菜单的Web应用示例1.1.1常规的Web级联菜单所存在的问题以前,为了避免每次对菜单的操作引起的重载页面,不采用每次调用后台的方式,而是一次性地将级联菜单的所有数据全部读取出来并写入到数组中,然后根据用户的操作用JavaScript+CSS来控制它的子集项目的显示,这样虽然解决了操作响应的速度、不重载页面以及避免向服务器频繁发送请求的问题,但是如果用户不对菜单进行操作或者只对菜单中的一部分进行操作的话,那读取的数据中的一部分就会成为多余而浪费用户的资源,特别是在菜单的结构复杂、数据量大的情况下,这样的弊端就更为突出!而如果采用AJAX技术来实现(JavaScript+CSS+AJAX),在页面初始化的时候,我们只需要读出其一级菜单的数据并显示出。
而在用户操作时,则通过AJAX向后台请求其下一级的菜单数据并显示出------这样,需要什么就下载什么!1.1.2构建本示例的Web应用项目1、添加一个JSP页面ajaxMenu.jsp(1)创建ajaxMenu.jsp页面文件(2)在该页面中添加一个表格,并且在其中放上超链接<%@ page language="java" pageEncoding="GB18030"%><%@ taglib uri="/tags-bean" prefix="bean" %><%@ taglib uri="/tags-html" prefix="html" %><%@ taglib uri="/tags-logic" prefix="logic" %><%@ taglib uri="/tags-tiles" prefix="tiles" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html:html lang="true"><head><html:base /><script language="javascript" src="ajaxMenu.js"></script><title>ajaxMenu1.jsp</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"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><table width="200" border="0" cellspacing="0" cellpadding="0"> <tr><td height="20"><a href="#" onclick="showSubMenu('menu_1')" >菜单一</a></td></tr><tr><td height="20" id="menu_1" style="display:none"> </td></tr><tr><td height="20"><a href="#" onclick="showSubMenu('menu_2')">菜单二</a></td><tr ><td height="20" id="menu_2" style="display:none"> </td></tr></table></body></html:html>(3)ajaxMenu.jsp页面文件的预览示图2、再添加JavaScript的文件ajaxMenu.js(1)创建JavaScript文件ajaxMenu.js(2)编程ajaxMenu.js文件中的功能实现代码var httpRequest;var currentPos;function showSubMenu(newCurrentPos){document.getElementById(newCurrentPos).parentNode.style.display="";currentPos=newCurrentPos;if(document.getElementById(newCurrentPos).style.display == "none"){document.getElementById(newCurrentPos).style.display = "";sendRequest("/AJAXWebApp/ajaxmenu.do?playPos="+newCurrentPos);}else{document.getElementById(newCurrentPos).style.display = "none";}}function sendRequest(requestURL){httpRequest=getHTTPRequestObject();httpRequest.onreadystatechange = processHttpResponse;httpRequest.open("GET", requestURL, true); // Get 请求方式的代码httpRequest.send(null);}function getHTTPRequestObject(){var httpRequestObject;if (window.XMLHttpRequest){ // Mozilla, Safari, ...httpRequestObject = new XMLHttpRequest();}else if (window.ActiveXObject){ // IEtry{httpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");}catch (e){try{httpRequestObject= new ActiveXObject("Msxml2.XMLHTTP");}catch (e2){alert("您的浏览器有问题!");}}}return httpRequestObject;}function processHttpResponse (){if (httpRequest.readyState == 4){if (httpRequest.status == 200){ //检查是否成功接收了服务器响应parseResponseText();}else if(httpRequest.status == 404){alert("没有找到与所请求的文件相匹配的资源!");}else{alert("你所请求的页面发生异常,错误代码为:"+httpRequest.status);}}else{document.getElementById(currentPos).innerHTML = "检测中,请稍等...";}}function parseResponseText(){document.getElementById(currentPos).innerHTML=httpRequest.responseText;}function LoadJS(file) //动态加载JS文件{var head = document.getElementsByTagName('HEAD').item(0);var script = document.createElement('SCRIPT');script.src = file;script.type = "text/javascript";head.appendChild(script);}3、添加一个Action类(1)切换到可视化设计视图(2)设置类名称为AjaxMenuAction,程序包名称为com.px1987.webajax.action /ajaxmenu(3)将产生出下面的Action类(4)编程AjaxMenuAction程序类中的功能实现方法package com.px1987.webajax.action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import java.io.*;public class AjaxMenuAction extends Action{public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {response.setContentType("text/html; charset=GBK");try{PrintWriter out = response.getWriter();String playPos = request.getParameter("playPos");if(playPos.equals("menu_1")){ //实际可以访问数据库表来获得各个子菜单项目String subMenuText=" <a href='#'>菜单一中的子菜单一</a><br>"+" <a href='#'>菜单一中的子菜单二</a><br>"+" <a href='#'>菜单一中的子菜单三</a>";out.write(subMenuText);out.close();}else if(playPos.equals("menu_2") ){String subMenuText=" <a href='#'>菜单二中的子菜单一</a><br>"+" <a href='#'>菜单二中的子菜单二</a><br>"+" <a href='#'>菜单二中的子菜单三</a><br>"+" <a href='#'>菜单二中的子菜单四</a>";out.write(subMenuText);out.close();}}catch(IOException e){System.out.println(e.getMessage());}return null;}}4、执行该功能(1)部署本示例项目(2)输入http://127.0.0.1:8080/StrutsAJAXWebApp/ajaxMenu.jsp(3)点击上面的菜单的链接,将展开对应的菜单项目(4)如果再次点击上面的菜单的链接,将关闭对应的菜单项目。
在一个jsp页面实现二级下拉框联动,实时读取数据库数据
在一个jsp页面实现二级下拉框联动,实时读取数据库数据,这个方法非常使用,只需要修改很小的地方就可以使用。
设计的文件,serch.jsp,main.js,bytetostr.js,先讲一下main.js,这是javascript,其中注意修改jsp页面名称。
function findObject(fName,initValue)...{var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");xmlhttp.open("POST","searchmx.jsp?findObject="+fName+"&initValue="+initValue,false);//注意修改jsp页面xmlhttp.send();document.getElementById(fName).innerHTML=bytes2BSTR(xmlhttp.responsebody); //bytes2BSTR函数在bytetostr.js中}其次为bytetostr.js,这是vbscript,这个不需要修改任何内容,他的主要功能就是读取数据转换字符串用的。
Function bytes2BSTR(vIn)dim istrReturn = ""For i = 1 To LenB(vIn)ThisCharCode = AscB(MidB(vIn,i,1))If ThisCharCode < &H80 ThenstrReturn = strReturn & Chr(ThisCharCode)ElseNextCharCode = AscB(MidB(vIn,i+1,1))strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))i = i + 1End IfNextbytes2BSTR = strReturnEnd Function接下来就是serch.jsp页面,只需要修改div中的id为你想要的名字,再将一开始的包更换一下,已经sql语句改下就可以了,有不明白的可以参与讨论<%@ page contentType="text/html; charset=gb2312" language="Java"import="com.sjth.zdsygl.vo.*,.*,java.util.*,com.sjth.zdsygl.jdbc.*,java.sql.ResultSet"%>//导入相应的包<%//这部分代码用于执行查询数据库,返回字符串if (request.getParameter("findObject")!=null)...{if (request.getParameter("findObject").equals("hy_dm"))...{DBConnect conn = null;ResultSet rs = null;try...{out.print("<select name='hy_dm' onchange="javascript:findObject('hymx_dm',this.value)">");String sql = "select * from dm_hy group by left(hy_dm,7)";conn = new DBConnect();conn.setPstmt(sql);rs = conn.executeQuery(sql);while(rs.next())...{out.print("<option value='"+rs.getString("hy_dm")+"'>"+rs.getString("hy_mc")+"</option>");}out.print("</select>");}catch (Exception e)...{}finally...{try...{if (rs != null)rs.close();if (conn != null)conn.close();}catch (Exception e)...{e.printStackTrace();}}}if (request.getParameter("findObject").equals("hymx_dm"))...{DBConnect conn = null;ResultSet rs = null;try...{out.print("<select name='hymx_dm' >");String sql = null;if (request.getParameter("initValue").equals(""))...{sql = "select * from dm_hy";}else...{sql = "select * from dm_hy where hy_dm like '"+request.getParameter("initValue")+"%'";}conn = new DBConnect();conn.setPstmt(sql);rs = conn.executeQuery(sql);while(rs.next())...{out.print("<option value='"+rs.getString("hy_dm")+"'>"+rs.getString("hy_mc")+"</option>");}out.print("</select>");}catch (Exception e)...{}finally...{try...{if (rs != null)rs.close();if (conn != null)conn.close();}catch (Exception e)...{e.printStackTrace();}}}return;}%><html><head><link href="Css/table.css" type="text/css" rel="stylesheet"><script language=vbscript src="css/bytetostr.js"></script><script language=javascript src="css/main.js"></script>//导入两个js文件</head><body><div>所属行业:</div><div id="hy_dm"></div> //用来显示返回的字符串<div >所属明细行业:</div><div id="hymx_dm"></div>//用来显示返回的字符串</body></html><script language="javascript">findObject("hy_dm","");findObject("hymx_dm","");//这两条是页面执行是调用</script>。
Ajax 实现级联菜单
Ajax 实现级联菜单关键字: ajax 级联菜单自己动手实现的一个Ajax级联菜单,开发平台:Eclipse,数据库:MySQL。
数据库设计如下图所示:1. 前台实现:Html代码1.<%@ page language="java"contentType="text/html; charset=UTF-8"2.pageEncoding="UTF-8"%>3.<%@ page import="java.sql.*,java.io.*"%>4.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">5.<html>6.<head>7.<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">8.<title>Ajax级联菜单实现</title>9.<script language="JavaScript"type="text/javascript">10.<!--11.var cache = [];12.function getLevel2(){13. if(document.forms.LevelMenu.select1.selectedIndex == 0){14. //当一级菜单未被选中时,二级菜单保持初始状态15. document.forms.LevelMenu.select2.length = 1;16. return;17. }18. //如果当前二级分类没有缓存时,则从服务器获取数据19. if(!cache[document.forms.LevelMenu.select1.selectedIndex]){20. //创建跨浏览器的XMLHttpRequest对象21. var xmlhttp;22. try{23. //IE 5.024. xmlhttp = new ActiveXObject('Msxm12.XMLHTTP');25. }catch(e){26. try{27. //IE 5.5 及更高版本28. xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');29. }catch(e){30. try{31. //其他浏览器32. xmlhttp = new XMLHttpRequest();33. }catch(e){}34. }35. }36. xmlhttp.open("get","ShowTwoMenu.jsp?id="+document.forms.LevelMenu.select1.value);37. xmlhttp.onreadystatechange = function(){38. if(xmlhttp.readyState == 4){39. if(xmlhttp.status == 200){40. cache[document.forms.LevelMenu.select1.selectedIndex] = eval("("+xmlhttp.responseText+")");41. getLevel2();42. }43. }44. }45. xmlhttp.send(null);46. return;47. }48. document.forms.LevelMenu.select2.length = 1;49. var _arr = cache[document.forms.LevelMenu.select1.selectedIndex];50. for (var i=0; i<_arr.length-1; i+=2){51. with(document.forms.LevelMenu.select2){52. options[options.length] = new Option(_arr[i], _arr[i+1]);53. }54. }55.}56.//-->57.</script>58.</head>59.<body>60.<%61. //驱动器名62. //数据库用户名和密码63. String userName = "root";64. String userPasswd = "1984428";65. //需要连接的数据库名66. String dbName = "studyajax";67. //表名68. String tableName = "articleType";72. "jdbc:mysql://localhost:3306/" + dbName, userName,73. userPasswd);74. Statement statement = conn.createStatement();75. String sql = "SELECT * FROM " + tableName + " where level=0";76. ResultSet rs = statement.executeQuery(sql);77.%>78.<form name="LevelMenu"><select name="select1"id="select1"79. onchange="getLevel2()">80. <option value="0">请选择一级分类:</option>81. <%82. while (rs.next()) {83. %>84. <option value="<%=rs.getInt(1) %>"><%=rs.getString(2)%></option>85. <%86. }87. rs.close();88. statement.close();89. conn.close();90. %>91.</select><select name="select2"id="select2">92. <option value="0">请选择二级分类</option>93.</select></form>94.95.</body>96.</html>2. 后台代码实现Html代码1.<%@ page language="java"contentType="text/html; charset=UTF-8"2.pageEncoding="UTF-8"%>3.<%@ page import="java.sql.*,java.io.*"%>4.<%5. //数据库用户名和密码6. int id = Integer.parseInt(request.getParameter("id").trim());7. //System.out.println("id:"+id);8. String userName = "root";9. String userPasswd = "1984428";10. //需要连接的数据库名11. String dbName = "studyajax";12. //表名13. String tableName = "articletype";17. "jdbc:mysql://localhost:3306/" + dbName, userName,18. userPasswd);19. Statement statement = conn.createStatement();20. String sql = "SELECT id, name FROM " + tableName21. + " where level=1 and parentId=" + id;22. //System.out.println("sql:"+sql);23. ResultSet rs = statement.executeQuery(sql);24.25. //获取数据结果集26. response.setContentType("text/html; charset=UTF-8");27. response.setHeader("Cache-Control", "no-cache");28. PrintWriter pout = null;29. pout = response.getWriter();30. pout.print("[");31. while (rs.next()) {32. try {33.34. pout.print("'" + (rs.getString("name")) + "',");35. pout.print(rs.getString("id"));36. pout.print(",");37. } catch (Exception e) {38. e.printStackTrace();39. }40. }41. pout.print("0]");42. rs.close();43. statement.close();44. conn.close();45.%>。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
while(category.next()){
%>
<option value="<%=category.getString(1) %>" ><%=category.getString(3) %> </option>
<%}}catch (SQLException e) {
if(resultDoms.length>0){
for(var i=0;i<resultDoms.length;i++)
{
option = document.createElement("option");
results=resultDoms[i].getElementsByTagName("kindid");
}
function handleStateChangeKind(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
updateList("kind");
}else {
alert("Not able to retrieve description : " +xmlHttp.status+" -- "+ xmlHttp.statusText);
var optionValue = selectList.options[selectList.selectedIndex].value;
var url="AjaxLists?"+ createQueryString("category" ,optionValue);
createXMLHttpRequest();
e.printStackTrace();
}finally{
data.close();
} %>
</select>
书籍小类:
<select id="kind" onchange="bookList()">
<option value="0">ALL </option>
//alert(xmlDoc);
models.innerHTML= xmlDoc;
}
function clearElements(id){
var models= document.getElementById(id);
while(models.childNodes.length>0){
models.appendChild(option);
}
}
}
function updateBook(id){
var models= document.getElementById(id);
var xmlDoc= xmlHttp.responseText;
xmlHttp.send(null);
}
function createQueryString(option ,optionValue){
var str="option="+option + "&optionValue="+optionValue;
return str;
本人实现了 ajax 异步实现 两级联动 的下拉列表 和 分类显示数据:
应该算是充分的实现例子, 包含了 JS + CSS 的简单设计
显示: 显示书籍大类 ----> 无刷新的显示相对应的书籍小类 ;
选择 书籍小类时候,自动显示相应的 书籍信息!
// 给Dao中查询一个标记
option.appendChild(document.createTextNode("all"));
model
// alert(models.options[0].value);
/*
}
}else{
document.getElementById("books").innerHTML="<font color='red'> Loading..... </font>";
}
}
function refreshList(){
var selectList = document.getElementById("category");
models.removeChild(models.childNodes[0]);
}
}
</script>
<style type="text/css">
table{
width: 500px;
text-align: center;
font: bold fantasy 25px;
option.setAttribute("value", results[0].firstChild.data);
results=resultDoms[i].getElementsByTagName("kindname");
option.appendChild(document.createTextNode(results[0].firstChild.nodeValue));
var url="AjaxLists?"+ createQueryString("kind" ,optionValue);
createXMLHttpRequest();
xmlHttp.onreadystatechange= handleStateChangeBook;
xmlHttp.open("GET", url, true);
createXMLHttpRequest();
var url="AjaxLists?";
xmlHttp.onreadystatechange= handleStateChangeKind;
url=url+createQueryString("category","1");
xmlHttp.open("GET", url, true);
// alert(xmlHttp.responseText);
clearElements(id);
var option= null;
option = document.createElement("option");
option.setAttribute("value", "0"+resultDoms[0].getElementsByTagName("kindid")[0].firstChild.data);
-->
<script type="text/javascript">
var xmlHttp;
window.onload=displayAll;
// 创建XMLHttpRequest对象
function createXMLHttpRequest(){
if (window.XMLHttpRequest)
自己试试吧,试试才知道,很好用的
纯手写的实例,仅供学习探究!
Jsp页面:
<%@ page language="java" import="java.util.*,com.AjaxDemo.optionLists.Dao,java.sql.*;"
contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
}
td{
height:35px;
width: 95px;
border-bottom-width:1px;
border-bottom-color: orange;
border-bottom-style: solid;
}
</style>
</head>
xmlHttp.send(null);
}
function bookList(){
var selectList = document.getElementById("kind");
var optionValue = selectList.options[selectList.selectedIndex].value;
}
}
}
function handleStateChangeBook(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
updateBook("books");
}else {
alert("Not able to retrieve description : " +xmlHttp.status+" -- "+ xmlHttp.statusText);