ajax+php实例动态二级联菜单效果
很多朋友都是用js来实现级联菜单了,那样有一个不好就是更新可能要修改源码,现在提供的这款ajax+php是一个实时的,不好之处在于耗费服务器资源了。
main.php
<script language="javascript" src="initajax.js"></script><!--InitAjax()-->
<script>
<!--
function getoption(select1,target) { if(select1.value!=0){ //select1是提交数据的来源的select菜单名 var url = "getoption.php?pid="+select1.value;//取得xml的url //alert(url); var ajax = InitAjax(); var i = 0; ajax.open("GET", url, true); ajax.onreadystatechange = function() { //如果执行是状态正常,那么就把返回的内容赋值给指定的地方 if (ajax.readyState == 4 && ajax.status == 200) { var obj = ajax.responseXML; var properties = obj.getElementsByTagName("property"); var name,value; target.options.length = 1; for (var i=0,x=1;i<properties.length;i++,x++) { name = properties[i].getElementsByTagName("name")[0].firstChild.nodeValue; value = properties[i].getElementsByTagName("value")[0].firstChild.nodeValue; target.options[x] = new Option(); target.options[x].text = name; target.options[x].value = value; } } } ajax.send(null); } }
<form method="post" name="form" action="index.php"> <select name="level1" onchange="getoption(document.form.level1,document.form.level2);"/> <option selected="ture" value="0">===选择===</option> <? if ($nrows>0){ for ($i=0;$i<$nrows;$i++){ echo "<option value="{$results[ID][$i]}">{$results[NAME][$i]}</option>"; } } ?> </select> <select name="level2" onchange="getoption(document.form.level2,document.form.level3);"> <option selected="ture" value="0">===选择===</option> </select>
iniajax.js:
function InitAjax() { var ajax = false; try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { ajax = false; } } if (!ajax && typeof XMLHttpRequest != 'undefined') { ajax = new XMLHttpRequest(); } return ajax; }
getoption.php:
<?php if($pid=$_GET["pid"]) { header("Content-type: text/xml;charset=GB2312"); echo "<?xml version=\"1.0\" encoding=\"GB2312\"?>"; include("./oracle.inc"); $sql="select * from AJAXTEST where PARENTID = $pid"; //echo $sql; $stmt=ociparse($handle,$sql); ociexecute($stmt); ocicommit($handle); ocilogoff(); $nrows=ocifetchstatement($stmt,$results); echo "<properties>"; //echo "<row>{$nrows}</row>"; for ($i=0;$i<$nrows;$i++){ echo "<property>"; echo "<value>{$results[ID][$i]}</value>"; echo "<name>{$results[NAME][$i]}</name>"; echo "</property>"; } echo "</properties>"; } ?>
永久链接:http://www.phprm.com/code/360fdbd32b43f29d4b68d0b7c5ddd765.html
转载随意!带上文章地址吧。