动态填充的下拉框
在此示例中,我们的目标是创建一个动态下拉框,其中第二个下拉列表中的选项框取决于第一个下拉框中所做的选择。
这是您的修改版本代码:
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_php_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中文网其他相关文章!