動態填充的下拉框
在此範例中,我們的目標是建立動態下拉框,其中第二個下拉清單中的選項框取決於第一個下拉框中所做的選擇。
這是您的修改版本程式碼:
tester.php
<html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $(function() { $('#stSelect').change(function() { var sel_stud = $(this).val(); $.ajax({ type: "POST", url: "another_php_file.php", data: 'theOption=' + sel_stud, success: function(whatigot) { $('#LaDIV').html(whatigot); } }); }); }); </script> </head> <body> <select name="students">
another_p hp_file.php
<?php $server = 'localhost'; //localhost is the usual name of the server if apache/Linux. $login = 'root'; $pword = ''; $dbname = 'test'; mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error()); mysql_select_db($dbname) or die($connect_error); //Get value posted in by ajax $sel_stud = $_POST['theOption']; //Run DB query if($sel_stud == "Electronics"){ $query = "SELECT * FROM `category` WHERE `master` = 1"; }elseif($sel_stud == "Clothes"){ $query = "SELECT * FROM `category` WHERE `master` = 2"; }else{ $query = "SELECT * FROM `category` WHERE `master` = 3"; } $result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error()); $num_rows_returned = mysql_num_rows($result); //Prepare response html markup $r = ' <select> '; //Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters if ($num_rows_returned > 0) { while ($row = mysql_fetch_assoc($result)) { $r = $r . '<option value="' .$row['id']. '">' . $row['name'] . '</option>'; } } else { $r = '<p>No Items</p>'; } echo $r;
在此範例中,選項第二個下拉方塊中的內容將根據第一個下拉方塊中選取的值動態填入。類別表已修改為包含一個主字段,用於對第二個下拉框中的選項進行分組。
以上是如何使用 PHP 和 AJAX 建立動態填滿的依賴下拉方塊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!