search
HomeBackend DevelopmentPHP TutorialPHP implements three-level cascading drop-down box, _PHP tutorial

php implements three-level cascading drop-down box,

This is the information I found on the Internet about php implementing three-level cascading drop-down box. Share it with everyone and let us make progress together. , the specific content is as follows

index.php:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Ajax联动菜单</title>
<script language="javascript" type="text/javascript" src="aa.js"></script>
</head>
<body>
<form>
<label>
<select name="sel" id="sel" onChange="showMenu(this.value);">
 <option>一级分类</option>
<&#63;php
$conn = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
mysql_select_db('fitment', $conn) or die ('Can\'t use database : ' . mysql_error());
mysql_query("set names 'gb2312'");
$str = "SELECT * FROM `fitment_sort` where supid = '0' ORDER BY `id` ASC";
$result = mysql_query($str) or die("Invalid query: " . mysql_error());
if($result)   while ($arr = mysql_fetch_array($result)){
    echo <<<EOD
<option value={$arr["id"]}>{$arr["name"]}</option>
EOD; }
mysql_close($conn);
&#63;>
</select>
</label>
<label>
<select name="sel2" id="sel2" onChange="showMenu2(this.value)">
 <option>二级分类</option>
 </select>
</label>
<label>
<select name="sel3" id="sel3">
 <option>三级分类</option>
</select>
</label>
</form>
<input type=button value="send value" onClick="alert(document.getElementByIdx_x_xx_x_xx('sel').options[document.getElementByIdx_x_xx_x_xx('sel').selectedIndex].text + '-' + document.getElementByIdx_x_xx_x_xx('sel2').options[document.getElementByIdx_x_xx_x_xx('sel2').selectedIndex].text + '-' + document.getElementByIdx_x_xx_x_xx('sel3').options[document.getElementByIdx_x_xx_x_xx('sel3').selectedIndex].text)">
</body>
</html>

aa.js

<!--
var xmlHttp
var xmlHttp2
//函数showMenu(str) - 功能函数1
function showMenu(str) xmlHttp=GetXmlHttpObject()    //调用GetXmlHttpObject()函数,创建XMLHttpRequest对象
if (xmlHttp==null)        //如果创建失败,则 alert ("Browser does not support HTTP Request")
 return 
var url="get2.php"        //定义url , 其主要读取数据库
url=url+"&#63;q="+str
url=url+"&sid="+Math.random()  //Math对象的random方法,取随机数
xmlHttp.onreadystatechange=stateChanged //设置当XMLHttpRequest对象xmlHttp状态改变时调用的函数,注意函数名后不要添加小括号
xmlHttp.open("GET",url,true)  //使用XMLHttpRequest对象的open()方法 , 创建HTTP请求
xmlHttp.send(null)        //使用XMLHttpRequest对象的open()方法 , 发送HTTP请求
}
//函数showMenu(str) - 功能函数1
function showMenu2(str)
{
xmlHttp2=GetXmlHttpObject()    //调用GetXmlHttpObject()函数,创建XMLHttpRequest对象
if (xmlHttp2==null)        //如果创建失败,则 alert ("Browser does not support HTTP Request")
 return 
var url="get2.php"        //定义url , 其主要读取数据库
url=url+"&#63;q2="+str
url=url+"&sid="+Math.random()  //Math对象的random方法,取随机数
xmlHttp2.onreadystatechange=stateChanged2 //设置当XMLHttpRequest对象xmlHttp状态改变时调用的函数,注意函数名后不要添加小括号
xmlHttp2.open("GET",url,true)  //使用XMLHttpRequest对象的open()方法 , 创建HTTP请求
xmlHttp2.send(null)        //使用XMLHttpRequest对象的open()方法 , 发送HTTP请求
}
//函数BuildSel() , 根据返回的的字串 , 重新构建新的下拉菜单控件Select - 功能函数2
function BuildSel(str,sel)   //先清空原来的数据.
  sel.options.length=0;   var arrstr = new Array();   arrstr = str.split(",");
  if(str.length>0)      //循环
    for(var i=0;i<arrstr.length;i++)       var subarrstr=new Array();       subarrstr=arrstr[i].split("|");
      sel.options.add(new Option(subarrstr[1],subarrstr[0]));     sel.options[0].selected=true; }
//函数stateChanged() - 响应HTTP请求状态变化
function stateChanged() //判断XMLHttpRequest对象的readyState属性值是否为4,如果为4表示异步调用完成(注意:异步调用完成 不代表 异步调用成功)
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") //如果异步调用成功 --> XMLHttpRequest对象的status属性值为200 , html文件在本地运行,则xmlHttp.status的返回值为0,故应该加上xmlHttp.status==0
 if(xmlHttp.status==200 || xmlHttp.status==0)     //调用文档对象模型DOM的getElementById()方法查找html文件中的标签txtHint ,
     //innerHTML为IE浏览器中的属性,可以用来更改标签间文本的内容 ,
     //xmlHttp.responseText , 通过XMLHttpRequest的responseText属性来获取数据 responseText,结果为字符串;responseXML,结果为XML形式
//     document.getElementByIdx_x_xx_x_xx("txtHint").innerHTML=xmlHttp.responseText
     BuildSel(xmlHttp.responseText,document.getElementsByTagName_r("*").sel2)
     showMenu2(document.getElementsByTagName_r("*").sel2.value); }
}
//函数stateChanged() - 响应HTTP请求状态变化
function stateChanged2() //判断XMLHttpRequest对象的readyState属性值是否为4,如果为4表示异步调用完成(注意:异步调用完成 不代表 异步调用成功)
if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete") //如果异步调用成功 --> XMLHttpRequest对象的status属性值为200 , html文件在本地运行,则xmlHttp.status的返回值为0,故应该加上xmlHttp.status==0
 if(xmlHttp2.status==200 || xmlHttp2.status==0)     //调用文档对象模型DOM的getElementById()方法查找html文件中的标签txtHint ,
     //innerHTML为IE浏览器中的属性,可以用来更改标签间文本的内容 ,
     //xmlHttp.responseText , 通过XMLHttpRequest的responseText属性来获取数据 responseText,结果为字符串;responseXML,结果为XML形式
//     document.getElementByIdx_x_xx_x_xx("txtHint").innerHTML=xmlHttp.responseText
     BuildSel(xmlHttp2.responseText,document.getElementsByTagName_r("*").sel3) }
}
//函数GetXmlHttpObject() - 创建XMLHttpRequest对象,即创建一个异步调用对象
function GetXmlHttpObject() var xmlHttp=null;
try // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest(); catch (e) //Internet Explorer
 try  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); catch (e)  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
return xmlHttp; -->

get2.php

<&#63;php header('Content-Type:text/html;charset=GB2312'); $conn = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
mysql_select_db('fitment', $conn) or die ('Can\'t use database : ' . mysql_error());
mysql_query("set names 'gb2312'");
//如果传递过来q
if($_GET["q"]){
$strs = "SELECT * FROM fitment_sort WHERE supid=' ".$_GET["q"]."' ";
//echo $str;
$results = mysql_query($strs) or die("Invalid query: " . mysql_error());
if($results)   while ($arrs = mysql_fetch_array($results)){
    $strings .= $arrs["id"]."|".$arrs["name"].",";   }
  echo substr($strings,0,strlen($strings)-1); }
//如果传递过来q2
if($_GET["q2"]){
$str = "SELECT * FROM fitment_sort WHERE supid= '".$_GET["q2"]."'";
//echo $str;
$result = mysql_query($str) or die("Invalid query: " . mysql_error());
if($result)   while ($arr = mysql_fetch_array($result)){
    $string .= $arr["id"]."|".$arr["name"].",";   }   echo substr($string,0,strlen($string)-1); }
mysql_close($conn);
&#63;>

The above is the relevant code for implementing three-level cascading drop-down boxes in PHP. I hope it will be helpful for everyone to learn PHP programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1122180.htmlTechArticlephp realizes three-level cascading drop-down box. This is the php that I found on the Internet to realize three-level cascading drop-down box. Please share the information in the box with everyone so that we can make progress together. The specific content is as follows index.php: htmlh...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function