两天时间用AJAX写了个无限级的多级联动菜单(ajax+PHP构架)
- 格式:doc
- 大小:51.00 KB
- 文档页数:6
花了两天时间。
研究AJAX,终于独立完成一个无限组的多级菜单联动功能。
主要特点:就是HTML静态页面可以无刷新的与PHP动态角本文件及数据库交互(这也是AJAX的核心目的)。
以下把代码贴出来。
供大家参考指正:ajax.js文件(位于根目录下js子目录)var xmlHttp;function createXmlHttp(){if(window.XMLHttpRequest){xmlHttp=new XMLHttpRequest();}else{xmlHttp=new ActiveXObject("Microsoft.XMLHttp");}}basic_inc.php(位于根目录下/include子目录下)<?php$DB_SERVER="localhost";$DB_NAME="ajax";$DB_USER="root";$DB_PASSWORD="";?>conn.php(位于根目录下/include子目录下)<?phprequire_once("dir_inc.php");require_once($ROOT_DIR."include/basic_inc.php");@ $db=mysql_connect($DB_SERVER,$DB_USER) or die ("faile!".mysql_error());@mysql_select_db($DB_NAME);?>dir_inc.php(位于根目标下/include子目录下)<?php$ROOT_DIR="../";?>select_menu.html(位于根目录下是核心前台文件)<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>select_menu</title><script type="text/javascript" src="js/ajax.js">//这里引用创建xmlHttp对像的文件(对浏览器做过判断)</script><script type="text/javascript">var targetSelId; //申明一个全局变量用来存放当前要操作的对像的IDvar selArray;//申明一个全局数组。
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" >请选择。
【概述】1. 登陆功能是大多数全球信息站和应用程序必备的功能之一,在全球信息站开发中,ajax和php都是常用的技术手段,结合两者能够实现更加灵活、高效的用户登入界面。
2. 本文将介绍如何使用ajax和php实现登入界面,并通过一个具体案例来说明其实际操作过程,希望能给读者带来一定的启发和帮助。
【ajax和php的基本概念】3. ajax是一种在不重新加载整个网页的情况下,能够更新部分页面的技术。
通过ajax,网页可以在用户输入时即时地向服务器发送请求,从而达到快速更新页面的效果。
4. php是一种服务器端脚本语言,可以与数据库进行交互,处理表单数据、生成动态页面等。
【使用ajax+php实现登入界面的步骤】5. 第一步:创建HTML页面5.1 创建一个登入表单,包括用户名和密码输入框以及提交按钮。
5.2 在页面中引入jquery库,以便于使用ajax进行数据交互。
6. 第二步:编写ajax代码6.1 使用jquery的ajax方法,在用户点击登入按钮时,将用户名和密码发送到服务器。
6.2 在ajax的回调函数中处理服务器返回的数据,如登入成功则跳转到主页,登入失败则提示错误信息。
7. 第三步:编写php代码7.1 接收ajax发送的用户名和密码数据,与数据库中的用户信息进行匹配。
7.2 登入成功则返回一个json格式的成功信息,登入失败则返回失败信息。
8. 第四步:创建数据库并添加用户信息8.1 创建一个用户表,存储用户的用户名和密码。
8.2 使用phpMyAdmin或其他数据库管理工具,向用户表中插入一个测试用户的信息。
【案例分析】9. 假设我们要实现一个简单的用户登入界面,包括用户名和密码输入框以及登入按钮。
用户输入正确的用户名和密码后,跳转至主页;输入错误则提示错误信息。
10. 创建HTML页面10.1 新建一个login.html文件,包括用户名和密码的输入框以及一个登入按钮。
10.2 引入jquery库,并编写javascript代码,使用ajax将用户名和密码发送至服务器。
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(网站、平台、系统等)开发,凭借其开发产品的非凡速度、领先的技术优势、富于创新的开发团队,为众多行业门户、专业型站点提供最有优质的服务和技术保障。
PHP+Ajax三级联动菜单PHP+Ajax 三级联动菜单PHP+Ajax实例+注释演示2009-08-26 13:01一.使用ajax有以下固定步骤:1, 从页面触发Ajax的操作.2, 定义创建XMLHttpRequest对象的方法(建立一个XMLHttpRequest对象),也是就var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//根据浏览器的不同有差异3, 然后建立一个函数,用来指定载入的数据来源!3.1,使用open方法打开数据来源(也就是我们要传入参数到DB查询的信息),但不意味着一定要发送数据显示!3.2,用onreadystatechange来指定数据装载的方式.(onreadystatechange是一个异步响应事件,就是因为它,ajax才那么完美.onreadystatechange事件中可以接收到服务器传回来的数据,通过分析和利用这些数据从而完成客户端的相应操作,onreadystatechange中的第三个参数你设为true,表示启用xmlHttp的异步通讯模式,这时你发出send命令后,浏览器还可以进行其它操作,如果设为false,浏览器就会进入无响应状态,直到xmlHttp接收完毕服务器传回的数据)3.3,使用send发送数据!4, 处理Ajax回传的数据(xml或text类型),使数据能按你的意愿现实在客户端.5, 回显到页面给用户.二,在网上看了一些资料,自己修改后,小小的整理主要出核心代码+精彩注释,全部贡献:index.php 客户端显示,包括执行AJAX的过程data.php 数据处理,查询数据,并回显/*************************index.php**********************/<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><!-------------------------------------------------------------- --省的字段是:province--市的字段是:city--县的字段是:area---------------------------------------------------------------------------><script type="text/javascript">/*********定义创建XMLHttpRequest对象的方法***************************************/var xmlHttp;//声明变量var requestType="";//声明初始类型为空function createXMLHttpRequest()//定义创建一个跨浏览器函数的开头{if(window.ActiveXObject)//ActiveXObject对象到找到的时候返回的是真,否则是假{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");//这个是使用IE的方法创建XmlHttp}else if(window.XMLHttpRequest){xmlHttp=new XMLHttpRequest();//这个是使用非IE的方法创建XmlHttp}}/****************判断服务器响应的事件,如果返回是4则说明交互完成,判断标示头,**************************************************/function handleStateChange(){//判断返回的一个函数,来确定执行那个的函数if(xmlHttp.readystate==4){//4说明是执行交互完毕0 (未初始化)1 (正在装载)2 (装载完毕) 3 (交互中)4 (完成)if(xmlHttp.status==200){//http的一个报头说明成功找到if(type=="city"){//判断查询的类型showcity();//返回响应的显示}else if(type="area"){//判断响应的查询的类型showarea();//返回响应的显示}}}}/**************************城市的一个查询函数**********************************************************/function queryCity(citycode){//执行程序查询,查询城市的eval("document.form1.city.length=0;");//eval检查JScript 代码并执行.eval("document.form1.city.options.add(new Option('请选择城市','-1'));");createXMLHttpRequest();//调用创建XmlHttp的函数type="city";//表示类型,查询城市处理显示的时候需要用到varurl='data.php?provincecode='+citycode+'&n='+Math.random() ;//设定URL传值方法同时防止缓存xmlHttp.open("GET",url,true);//建立服务器连接,异步传输truexmlHttp.onreadystatechange=handleStateChange;//处理这个响应所需要的函数xmlHttp.send(null);//执行程序函数这里的中间的参数是因为GET原因}/**********************县区的一个查询函数***********************************************************/function queryArea(citycode){//查询程序eval("document.form1.area.length=0;");//eval检查 JScript 代码并执行.eval("document.form1.area.options.add(new Option('请选择县市','-1'));");createXMLHttpRequest();//调用创建XmlHttp的函数type="area";//查询县的varurl="data.php?citycode="+citycode+'&n='+Math.random();//设定URL传值方法同时防止缓存xmlHttp.open("GET",url,true);xmlHttp.onreadystatechange=handleStateChange;//处理响应的函数名xmlHttp.send(null);//执行程序函数这里的中间的参数是因为GET原因}/*********************一个显示函数*********************/function showcity(){//显示函数var a = xmlHttp.responseText.split('-');n = a.length;var aa = new Array();for(var i=0;i<n;i++){aa = a[i].split('**');eval("document.form1.city.options.add(newOption(aa[1],aa[0]));");//eval检查 JScript 代码并执行.}}function showarea(){var a = xmlHttp.responseText.split('-');n = a.length;var aa = new Array();for(var i=0;i<n;i++){aa = a[i].split('**');eval("document.form1.area.options.add(newOption(aa[1],aa[0]))");}//document.getElementById("area").innerHTML=xmlHttp.re sponseText;//捕获ID显示返回的数据}</script></head><body><?php$conn = mysql_connect("localhost","root","3661000");//链接数据库mysql_select_db("novel");//选择数据库mysql_query("set names 'utf8'");//设定字符集$sql = "select * from province";//查询数据库province表也就是省$result = mysql_query($sql);//执行语句赋值给变量><form name="form1"><!--输出表单头--><!--输出下拉列表框,并设定onchange响应事件,把省值传递过去--><select id='province' onchange='queryCity(this.options[this.selectedIndex].value)'> <!--输出下拉列表项值--><option value='-1' selected>请选择省份</option><?phpwhile($row=mysql_fetch_row($result)){//循环循环查询显示省输出数据显示echo "<option value='$row[1]'>$row[2]</option>\n";}></select><!--下拉列表项尾数--><select name="city" onchange="queryArea(this.options[this.selectedIndex].value)"></select> <!--显示数据的城市的位置--><select name="area"></select><!--显示数据的城市的位置--> </form><!--表单项结尾--></body></html>/***************data.php*****************/<?php$provincecode = $_GET['provincecode'];//接收省键值$citycode = $_GET['citycode'];//接收城市键值$conn = mysql_connect("localhost","root","3661000");//连接主机mysql_select_db("novel");//选择数据库mysql_query("set names 'utf8'");if($provincecode!=""){//如果传递过来的不为空则执行$sql = "select * from city where provincecode=$provincecode";//查询城市符合属于上边传递过来的省的字段$result = mysql_query($sql);//执行SQL查询语句while($row=mysql_fetch_row($result)){//循环记录集$xml .= $row[1]."**".$row[2]."-";}}if($citycode!=""){$sql = "select * from area where citycode=$citycode";$result = mysql_query($sql);while($row = mysql_fetch_row($result)){$xml .=$row[1]."**".$row[2]."-";}}$xml = substr($xml,0,strlen($xml)-1);//消掉最后的"-"echo $xml; //返回数据做回显。
mysqlphpajax使⽤jsonp跨域完成省市三级联动mysql php ajax 使⽤jsonp跨域完成省市三级联动mydb.sql⽤到了area,city,province 三个表cont.php 连接数据库data2.php 得到前端传过来的值,处理SQL语句,输出内容。
因为使⽤jsonp⽅式,就是输出函数名⾥⾯加上参数就可以了。
ajax的跨域问题可以看我ajax的⽂章<?phprequire_once('cont.php');$code = $_GET['citycode'];$callback = $_GET['callback'];$flag = $_GET['flag'];if($flag == 1){$retval= mysqli_query($conn,"select * from province order by id");}else if($flag == 2){$retval= mysqli_query($conn,"select * from city where provincecode = '".$code."' order by id" );}else if($flag == 3){$retval= mysqli_query($conn,"select * from area where citycode = '".$code."' order by id" );}// 创建⼀个空数据$sayList = [];// 循环遍历得到数据库内容while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)){$sayList[]= array('code'=>$row['code'],'name'=>$row['name']);//⼆维数组}// // 数组长度// echo count($sayList);// // 数组结构// print_r($sayList);// 循环遍历// for($i=0;$i<11;$i++){// for($j=0;$j<2;$j++){// echo $sayList[$i]['code']."-->".$sayList[$i]['name'];// }// }if($sayList){echo$callback.'('.json_encode($sayList).')';}else{echo$callback.'('.'[]'.')';}>select.html<!DOCTYPE html><html><head><meta charset="utf-8"><title></title><script src="jquery-1.11.2.js" type="text/javascript" charset="utf-8"></script><style type="text/css">#showInfo{position: absolute;width: 600px;height: 500px;overflow-y: scroll;overflow-x: hidden;background: lightgreen;left: 50%;margin-left: -300px;}#showInfo div{float:left;margin-left: 30px;margin-top: 30px;width: 160px;}#showInfo div select{width: 160px;}</style></head><body><div id="showInfo"><div><select id="province"></select></div><div><select id="city"></select></div><div><select id="area"></select></div></div><script type="text/javascript">$(function(){//获取列表数据的通⽤⽅法function getList(code,flag,callback){$.ajax({url:'data2.php',type:'get',dataType:"jsonp",data:{citycode:code,flag:flag},success:callback});}//获取地区信息的回调函数var area = function(data){$.each(data,function(i,element){var op = $("<option></option>").attr("value",data[i].code).append(data[i].name); $("#area").append(op);});}// 拼接市var city=function(data){for (var i = 0; i <data.length; i++) {var op = $("<option></option>").attr("value",data[i].code).append(data[i].name); $("#city").append(op);}// 判断是否是直辖市,即只有⼀个市if(data.length == 1){var citycode = $("#city").children("option").eq(0).attr("value");getList(citycode,3,area);}}// 拼接省var pr=function(data){for (var i = 0; i <data.length; i++) {var op = $("<option></option>").attr("value",data[i].code).append(data[i].name); $("#province").append(op);}//默认北京市getList('110000',2,city);getList('110100',3,area);}// 刚开始调⽤函数getList(1,1,pr)//给省份信息设置选择事件$("#province").change(function() {$("#city").children("option").remove();$("#area").children("option").remove();var pcode = $(this).val();getList(pcode,2,city);});//给省份信息设置选择事件$("#city").change(function() {$("#area").children("option").remove();var citycode = $(this).val();getList(citycode,3,area);});})</script></body></html>。
php实现菜单⽆限极分类⼀、数据表结构CREATE TABLE `t_admin_privilege` (`f_id` int(11) NOT NULL AUTO_INCREMENT,`f_name` varchar(50) DEFAULT NULL COMMENT '⽬录名称',`f_parent_id` int(11) DEFAULT '0' COMMENT '⽗级id',`f_type` tinyint(4) DEFAULT NULL COMMENT '第⼏级⽬录',`f_url` varchar(255) DEFAULT NULL COMMENT '⽬录的链接地址',`f_createtime` int(10) DEFAULT NULL COMMENT '创建时间',`f_is_menu` tinyint(1) DEFAULT '1' COMMENT '1是菜单栏 2不是菜单栏',`f_icon` varchar(50) DEFAULT NULL COMMENT '⼩图标',`f_is_del` tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否删除 1正在使⽤(未删除) 2删除',`f_sort` tinyint(5) DEFAULT NULL COMMENT '排序',PRIMARY KEY (`f_id`)) ENGINE=InnoDB AUTO_INCREMENT=335 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT⼆、后台取数据(使⽤Yii框架)header("content-type:text/html;charset=utf-8"); //避免提⽰中⽂乱码$html = array();//获取菜单栏所有的数据$menu_record = T_admin_privilege::model()->findAll();$EData = new EData();$html['menu_list'] = $EData->push_info($menu_record);//1级⽬录$criteria_first = new CDbCriteria();$criteria_first->addCondition("f_type=1 AND f_is_menu=1 AND f_is_del=1");$criteria_first->order="f_id";//2级⽬录$criteria_second = new CDbCriteria();$criteria_second->addCondition("f_type=2 AND f_is_menu=1 AND f_is_del=1");$criteria_second->order="f_id";//3级⽬录$criteria_third = new CDbCriteria();$criteria_third->addCondition("f_type=3 AND f_is_menu=1 AND f_is_del=1");$criteria_third->order="f_id";//4级⽬录$criteria_fourth = new CDbCriteria();$criteria_fourth->addCondition("f_type=4 AND f_is_menu=1 AND f_is_del=1");$criteria_fourth->order="f_id";$menu_array = array();//菜单分为4级$first_list = T_admin_privilege::model()->findAll($criteria_first);$html['first_num'] = $first_num = count($first_list);$second_list = T_admin_privilege::model()->findAll($criteria_second);$html['second_num'] = $second_num = count($second_list);$third_list = T_admin_privilege::model()->findAll($criteria_third);$html['third_num'] = $third_num = count($third_list);$fourth_list = T_admin_privilege::model()->findAll($criteria_fourth);$html['fourth_num'] = $third_num = count($fourth_list);//⼀级⽬录foreach ($first_list as$first){$menu_array[$first->f_id] = array();}//⼆级⽬录foreach ($second_list as$second){$menu_array[$second->f_parent_id][$second->f_id] = array();}//三级⽬录foreach ($third_list as$third){foreach ($menu_array as$first_k => $menu){foreach ($menu as$second_k => $next){if ($second_k == $third->f_parent_id){$menu_array[$first_k][$second_k][$third->f_id] = array();}}}}//四级⽬录foreach ($fourth_list as$fourth){foreach ($menu_array as$first_k=>$second_menu){foreach ($second_menu as$second_k => $third_menu){foreach ($third_menu as$third_k => $firth_menu){if ($third_k == $fourth->f_parent_id){$menu_array[$first_k][$second_k][$third_k][$fourth->f_id] = 0;}}}}}$html['menu_array'] = $menu_array;//把数据单独放在⼀个页⾯,通过ajax加载$out = array('error' => 0,'content' => $this->renderPartial("ajax_get_menu_list_page", $html, true));echo CJSON::encode($out);三、html页⾯(ajax_get_menu_list_page页⾯,在pixed-admin框架下,也可引⼊jQuery,bootstrap修改样式)<div class="col-sm-12 menu_list" id="menu_list"><!--遍历⼀级⽬录 start--><?php foreach ($menu_array as $k=>$first_menu){?><div class="first_menu_list"><div class="first_menu menu"><?php if(count($first_menu)>0) {?><a href='javascript:;' class="is_show" f_id="<?php echo $menu_list[$k]['f_id'];?>">+</a><?php }else{?><i style="padding: 0 9px"></i><?php }?><input type="text" class="first_title title" name="first_title" value="<?php echo $menu_list[$k]['f_name']?>" f_id="<?php echo $menu_list[$k]['f_id'];?>" f_parent_id="0"><?php if(count($first_menu)<1) {?><input type="text" placeholder="请填写⽬录的路径地址" f_id="<?php echo $menu_list[$k]['f_id']?>" value="<?php echo $menu_list[$k]['f_url']?>" class="path_address"<div class="operation"><?php if (empty($menu_list[$k]['f_url']) ){?><a class="btn btn-xs btn-add second_add">添加</a><?php }?><?php if (count($first_menu)<=1){?><a class="btn btn-xs btn-del del first_del" f_id="<?php echo $menu_list[$k]['f_id']?>">删除</a><?php }?></div></div><!--遍历⼆级⽬录 start--><?php if(count($first_menu)>0){foreach ($first_menu as $first_k=>$second_menu){?><div class="second_menu_list <?php echo $menu_list[$first_k]['f_parent_id'];?>"><div class="second_menu menu"><input type="text" class="second_title title" name="second_title" value="<?php echo $menu_list[$first_k]['f_name']?>" f_id="<?php echo $menu_list[$first_k]['f_id'];?>" f_parent_id="<?php echo $menu_list[ <?php if(count($second_menu)<1) {?><input type="text" placeholder="请填写⽬录的路径地址" f_id="<?php echo $menu_list[$first_k]['f_id']?>" value="<?php echo $menu_list[$first_k]['f_url']?>"<div class="operation"><?php if(empty($menu_list[$first_k]['f_url'])) {?><a class="btn btn-xs btn-add third_add">添加</a><?php }?><?php if (count($second_menu)<=1){?><a class="btn btn-xs btn-del del second_del" f_id="<?php echo $menu_list[$first_k]['f_id']?>">删除</a><?php }?></div></div><!--遍历三级⽬录 start--><?php if (count($second_menu)>0){foreach ($second_menu as $second_k=>$third_menu){?><div class="third_menu_list"><div class="third_menu menu"><input type="text" class="third_title title" name="third_title" value="<?php echo $menu_list[$second_k]['f_name']?>" f_id="<?php echo $menu_list[$second_k]['f_id']?>" f_parent_id="<?php echo $menu <?php if(count($third_menu)<1) {?><input type="text" placeholder="请填写⽬录的路径地址" f_id="<?php echo $menu_list[$second_k]['f_id']?>" value="<?php echo $menu_list[$second_k]['f_url']?>"<div class="operation"><?php if(count($third_menu)>1) {?><a class="btn btn-xs btn-add fourth_add">添加</a><?php }?><?php if (count($third_menu)<=1){?><a class="btn btn-xs btn-del del third_del" f_id="<?php echo $menu_list[$second_k]['f_id']?>">删除</a><?php }?></div></div><!--遍历四级⽬录 start--><?php if (count($third_menu)>0){foreach ($third_menu as $third_k=>$fourth_menu){?><div class="fourth_menu menu"><input type="text" class="fourth_title title" name="fourth_title" value="<?php echo $menu_list[$third_k]['f_name']?>" f_id="<?php echo $menu_list[$third_k]['f_id']?>" f_parent_id="<?php echo $menu<input type="text" placeholder="请填写⽬录的路径地址" f_id="<?php echo $menu_list[$third_k]['f_id']?>" value="<?php echo $menu_list[$third_k]['f_url']?>" class="path_address"/><div class="operation"><a class="btn btn-xs btn-del del fourth_del" f_id="<?php echo $menu_list[$third_k]['f_id']?>">删除</a></div></div><?php }}?><!--遍历四级⽬录 end--></div><?php }}?><!--遍历三级⽬录 end--></div><?php }}?><!--遍历⼆级⽬录 end--></div><?php }?><!--遍历⼀级⽬录 end--></div>四、html页⾯(menu_list_page页⾯,在pixed-admin框架下,也可引⼊jQuery,bootstrap修改样式)、<div class="page-body"><div class="panel"><div class="form-group " id="get_menu_list"></div></div></div>五、css样式 *{margin: 0;padding: 0;}.add {margin-right: 10px;}.menu_list { margin:0px 20px 40px 20px;position: relative}.menu { height: 25px;}.first_menu {font-weight: bolder; font-size: 20px;margin:30px 15px 0px 15px;}.second_menu { padding: 25px 45px; font-weight: bold; font-size: 16px;}.third_menu { padding: 20px 0px 20px 90px;font-size: 14px;}.fourth_menu{padding: 20px 135px;}input {padding-left: 10px;border: none;margin-right: 30px;}.manual_content { width:450px;}.manual_content::after{content: '';}.manual_content a{float: right;margin-right: 10px;}.manual_content a:active::after{content: '';}.ui-accordion-header{border: none;}.ui-accordion-header.ui-state-active:after{content:""}a{display: inline-block}a:link{text-decoration: none}a:active{text-decoration: none}a:visited{text-decoration: none}a:hover{text-decoration: none}/*.second_menu_list{display: none}*/.is_show{font-size: 30px;}.menu_list{padding-right: 60px;}.btn-del,.btn-add{margin: -30px 10px 0 10px;}.btn-add{position: absolute; right:35%;}.btn-del{position:absolute;right: 30%;}.menu .path_address{font-size: 14px;width:400px;margin-left: 30px;font-weight: normal}六、js//通过ajax,把数据加载到menu_list_page页⾯$.ajax({url : '/system/ajax_get_menu_list_page',type : 'post',async : false,data : {},dataType : 'json',success : function(res){if( res.error == 0){$("#get_menu_list").prepend(res.content);}else{}}});//添加其他⽅法动态实现⽬录的增删改查。
现在到处都有这方面的教程,我重点说一下我自己搞的一个框架。
特点:支持Form的无闪提交(方法有点笨)支持MVC框架,即支持传统网页架构多线程并发请求(要语言支持线程)动态加载文件,只加载有用的!处理了Ajax框架臃肿的JS文件问题。
采用no table的全div + css布局a. 获得XMLHTTPRequest对象,网上到处都找得到了,不多说:function newXMLHttpRequest() {var xmlreq = false;if (window.XMLHttpRequest) {xmlreq = new XMLHttpRequest();} else if (window.ActiveXObject) {try {xmlreq = new ActiveXObject("Msxml2.XMLHTTP");} catch (e1) {try {xmlreq = new ActiveXObject("Microsoft.XMLHTTP");} catch (e2) {}}}return xmlreq;}这里提供一个通用的支持多浏览器的方法。
b.提出异步请求//这里用Bcandy作为方法名是为了感谢一个对我来说很重要的人,她一直在支持我function Bcandy(Tid,url,parm,js) {if(url == ""){return;}//这是一个加载信息提示框,也可以不要!document.getElementById("load").style.visibility = "visible";//加载相应页面的JS文件if(js != null){//加载JS文件LoadJS(js);}// 获取一个XMLHttpRequest实例var req = newXMLHttpRequest();// 设置用来从请求对象接收回调通知的句柄函数var handlerFunction = getReadyStateHandler(req,Tid);req.onreadystatechange = handlerFunction;// 第三个参数表示请求是异步的req.open("POST", url, true);// 指示请求体包含form数据req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");// 发送参数req.send(parm);}function getReadyStateHandler(req,Tid) {// 返回一个监听XMLHttpRequest实例的匿名函数return function () {// 如果请求的状态是“完成”if (req.readyState == 4) {// 成功接收了服务器响应if (req.status == 200) {//下面一句是重点,这里显示了返回信息的内容部分,也可以加以修改。
AJAX实现省市县三级联动效果最近在学AJAX做到这个省市县三级联动的案例,这⾥只是讲⼀下ajax请求的⼀些知识,对服务端数据.php⽂件就不叙述了。
(tips:其实省市县三级联动只需要引⼊jQuery省市县三级联动插件就可以实现)效果图⾸先准备两个服务端⽂件,另⼀个⽂件太长,这⾥就不导⼊了selsect.php<?php/*省市县后台数据接⼝接⼝调⽤规则:1.参数⼀:flag,⽤来区分请求的是省市县中间的那种数据2.参数⼆:选择省的时候传递pid,选择市的时候传递cIdhttp://localhost/select.php?flag=1#pId=23*/// include('./selectdata.php');require('./selectdata.php');// 省市县数据来⾃selectdata.php⽂件$province = $provinceJson;$city = $cityJson;$county = $countyJson;$flag = $_GET['flag'];// 省级数据if($flag == 1){echo json_encode($province);// 市级数据}else if($flag == 2){$pId = $_GET['pId'];$cityData = array();foreach ($city as $value) {if($value->id == $pId){// 直辖市array_push($cityData,$value);break;}else if($value->parent == $pId){// ⾮直辖市array_push($cityData,$value);}}echo json_encode($cityData);// 县级数据}else if($flag == 3){$cId = $_GET['cId'];$countyData = array();foreach ($county as $value) {if($value->parent == $cId){array_push($countyData,$value);}}echo json_encode($countyData);}>select.html这⾥可以⽤底层ajax 请求,也可以⽤快捷⽅法 $.get ⽅法进⾏数据请求。
花了两天时间。
研究AJAX,终于独立完成一个无限组的多级菜单联动功能。
主要特点:就是HTML静态页面可以无刷新的与PHP动态角本文件及数据库交互(这也是AJAX的核心目的)。
以下把代码贴出来。
供大家参考指正:ajax.js文件(位于根目录下js子目录)var xmlHttp;function createXmlHttp(){if(window.XMLHttpRequest){xmlHttp=new XMLHttpRequest();}else{xmlHttp=new ActiveXObject("Microsoft.XMLHttp");}}basic_inc.php(位于根目录下/include子目录下)<?php$DB_SERVER="localhost";$DB_NAME="ajax";$DB_USER="root";$DB_PASSWORD="";?>conn.php(位于根目录下/include子目录下)<?phprequire_once("dir_inc.php");require_once($ROOT_DIR."include/basic_inc.php");@ $db=mysql_connect($DB_SERVER,$DB_USER) or die ("faile!".mysql_error());@mysql_select_db($DB_NAME);?>dir_inc.php(位于根目标下/include子目录下)<?php$ROOT_DIR="../";?>select_menu.html(位于根目录下是核心前台文件)<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>select_menu</title><script type="text/javascript" src="js/ajax.js">//这里引用创建xmlHttp对像的文件(对浏览器做过判断)</script><script type="text/javascript">var targetSelId; //申明一个全局变量用来存放当前要操作的对像的IDvar selArray;//申明一个全局数组。
用来存放级联菜单的数组// 获取列表选项的调用函数function buildSelect(selectedId,targetId){if(selectedId==""){//selectedId为空表示选中了默认项clearSubsel(targetId);//清除目村列表及下级列表的选项return;//直接结束调用,不必向服务器请求信息}createXmlHttp();//将传入的目标列表的Id赋值给TargetSelId变量targetSelId=targetId;//创建XmlHttpRequest对像//alert(targetSelId);xmlHttp.onreadystatechange=buildSelectCallBack; //设置回调函数xmlHttp.open("GET","select_menu.php?selectedId="+selectedId,true);xmlHttp.send(null);}//获取列表选项的回调函数function buildSelectCallBack(){if(xmlHttp.readyState==4){//将从服务器获得的文本转为对像直接量// alert("("+xmlHttp.responseT ext+")");var selectInfo=eval("("+xmlHttp.responseT ext+")");var targetSelNode=document.getElementById(targetSelId);clearSubSel(targetSelId);//清除列表及下级列表中的选项//遍历对像直接量中的成员for(var o in selectInfo){var option1 = document.createElement("option");//创建一个Option节点option1.value=o;//节点无素的值为o option1.appendChild(document.createT extNode(selectInfo[o]));//给节点加入文本信息targetSelNode.appendChild(option1);//把以上的节点信息创建在targetSelNode对像上}}}//根据传入的Value和Text创建选项,这个函数在这里边没有用到,直接在buildSelectCallBack函数中工作function createOption(value,text){var opt=document.createElement("option");opt.setAttribute("value",value);opt.appendChild(document.createT extNode(text));return opt;}//清除传入的列表节点内所有选项function clearOptions(selNode){selNode.length=1;//设置列表长度为1,仅保留默认选项selNode.options[0].selected=true;//选中默认选项}//清除下级子列表选项function clearSubSel(targetId){var canClear=false; //设置清除开关,初始化值为假for(var i=0;i<selArray.length;i++){//遍历列表数组//alert("targetId is:"+targetId+"|selArray-"+i+"is:"+selArray[i]);if(selArray[i]==targetId){canClear=true; //当遍历目标列表时,打开清除开关}//alert("canClear is:"+canClear);if(canClear){//从目标列表开始到最下级列表结束,开关始终保持打开clearOptions(document.getElementById(selArray[i]));//清除该级列表选项}}}//初始化列表数组(按等级)function initSelArray(){selArray=arguments;//alert(selArray);}</script></head><META HTTP-EQUIV="pragma" CONTENT="no-cache"><META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"><META HTTP-EQUIV="expires" CONTENT="0"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="generator" content="PSPad editor, "><title></title></head><!--页面加载完毕做两件事:1。
初始化列表数组2。
为第一个列表赋值--> <body onLoad="initSelArray('selA','selB','selC');buildSelect('INIT','selA')"> <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>select_menu.php(位于根目录下。