动态下拉框? [英] dynamic drop down box?
问题描述
我得到一个名为category的数据库表,如图所示:
我试图做一个动态的下拉框,索引脚本显示为:
<?php
try {
$ objDb = new PDO('mysql:host = localhost; dbname = test','root','');
$ objDb-> exec('SET CHARACTER SET utf8');
$ sql =SELECT *
FROM`category`
WHERE`master` = 0;
$ statement = $ objDb-> query($ sql);
$ list = $ statement-> fetchAll(PDO :: FETCH_ASSOC);
} catch(PDOException $ e){
echo'有问题';
}
?>
<!DOCTYPE HTML>
< html lang =en>
< head>
< meta charset =utf-8/>
< title>可靠下拉菜单< / title>
< meta name =descriptioncontent =可靠的下拉菜单/>
< meta name =keywordscontent =可靠的下拉菜单/>
< link href =/ css / core.css =stylesheettype =text / css/>
<! - [if lt IE 9]>
< script src =http://html5shiv.googlecode.com/svn/trunk/html5.js>< / script>
<![endif] - >
< script src =/ js / jquery-1.6.4.min.jstype =text / javascript>< / script>
< script src =/ js / core.jstype =text / javascript>< / script>
< / head>
< body>
< div id =wrapper>
< form action =method =post>
< option value =>选择一个< / option>
<?php if(!empty($ list)){?>
<?php foreach($ list as $ row){?>
< option value =<?php echo $ row ['id'];?>>
<?php echo $ row ['name']; ?>
< / option>
<?php}?>
<?php}?>
< / select>
disabled =disabled>
< option value => ----< / option>
< / select>
disabled =disabled>
< option value => ----< / option>
< / select>
< / form>
< / div>
< / body>
< / html>
update.php显示为:
< $($ _ GET ['id'])&&!empty($ _ GET ['value'])){pre $
<?php
b
$ b $ id = $ _GET ['id'];
$ value = $ _GET ['value'];
try {
$ objDb = new PDO('mysql:host = localhost; dbname = test','root','');
$ objDb-> exec('SET CHARACTER SET utf8');
$ sql =SELECT *
FROM`category`
WHERE`master` =?;
$ statement = $ objDb-> prepare($ sql);
$ statement-> execute(array($ value));
$ list = $ statement-> fetchAll(PDO :: FETCH_ASSOC);
if(!empty($ list)){
$ out = array('< option value =>选择一个< / option>');
foreach($ list as $ row){
$ out [] ='< option
value =''。$ row ['id']。'> ;。$行[ '名称'] '< /选项>';
echo json_encode(array('error'=> false,'list'=> implode('',
$ out)));
} else {
echo json_encode(array('error'=> true));
$ b $ catch(PDOException $ e){
echo json_encode(array('error'=> true));
}
} else {
echo json_encode(array('error'=> true));
}
第二个下拉框不显示依赖于第一个下拉列表的值如图所示:
有人可以帮我解决问题。
会做你想做的。从本质上讲,你可以使用jQuery / AJAX来实现这一点。
我更新了我的示例代码以匹配你的服务器登录/表/字段名称,所以如果你复制/两个示例到文件中(称它们为 tester.php
和 another_php_file.php
),那么您应该有一个完整的工作示例
我修改了下面的示例以创建第二个下拉框,其中填充了找到的值。如果你一行一行地遵循逻辑,你会发现它确实很简单。我留下了几条注释,如果没有注释(一次一个)会告诉你脚本在每个阶段都在做什么。
FILE 1 - TESTER.PHP
< html>
< head>
< script src =// ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\"> ;</script>
< script type =text / javascript>
$(function(){
// alert('Document is ready');
$ b $('#stSelect')。change(function(){
var sel_stud = $(this).val();
// alert('You pick:'+ sel_stud);
$ .ajax({
type: POST,
url:another_php_file.php,
data:'theOption ='+ sel_stud,
成功:函数(whatigot){
// alert('Server- (+);
$('#LaDIV')。html(whatigot);
$('#theButton')。click(function(){
alert('您点击了按钮');
});
} // END success fn
)); // END $ .ajax
}); // END下拉更改事件
}); // END document.ready
< / script>
< / head>
< body>
< option value =>请选择< / option>
< option value =John> John Doe< / option>
< option value =Mike> Mike Williams< / option>
< option value =Chris> Chris Edwards< / option>
< / select>
< div id =LaDIV>< / div>
< / body>
< / html>
文件2 - another_php_file.php
<?php
//登录到数据库(通常这存储在一个单独的php文件中并包含在每个需要的文件中)
$ server ='localhost'; // localhost是服务器的常用名称,如果apache / Linux。
$ login ='root';
$ pword ='';
$ dbname ='test';
mysql_connect($ server,$ login,$ pword)或die($ connect_error); //或死(mysql_error());
mysql_select_db($ dbname)或die($ connect_error);
//获取由ajax发布的值
$ selStudent = $ _POST ['theOption'];
//死('您发送:'。$ selStudent);
//运行数据库查询
$ query =SELECT * FROM`category` WHERE`master` = 0;
$ result = mysql_query($ query)或者死('Fn another_php_file.php错误:'。mysql_error());
$ num_rows_returned = mysql_num_rows($ result);
// die('Query returned'。$ num_rows_returned。'rows。');
//准备回应html标记
$ r ='
< h1>在数据库中找到:< / h1>
< select>
';
//解析mysql结果并创建响应字符串。如果($ num_rows_returned> 0){
while($ row = mysql_fetch_assoc($ result)){
$(
)),响应可以是一个html表,一个完整页面或几个字符
r = $ r。 '< option value =''。$ row ['id']。'>'。 $ row ['name']。 < /选项>;
}
}其他{
$ r ='< p>没有学生在该名称上的员工< / p>';
}
//添加额外的按钮以获得乐趣
$ r = $ r。 '< / select>< button id =theButton>点击我< /按钮>';
//下面回显的响应将被插入
echo $ r;
要在评论中回答您的问题:How你是否使第二个下拉框填充仅与第一个下拉框中的选定选项相关的字段?
A。在第一个下拉菜单的 .change
事件中,您读取了第一个下拉框的值:
$('#dropdown_id')。change(function(){
var dd1 = $('#dropdown_id')。val();
)
在上述
.change()
事件中,您将该变量包含在您发送到第二个.PHP文件的数据中(在我们的例子中为another_php_file.php) success中访问它们:
部分的AJAX函数 这就是我在上面发布的示例中所做的:
-
用户选择一个学生姓名, jQuery
.change()
选择器 -
以下是抓取用户所选选项的行: c $ c> var sel_stud = $(this).val();
-
c> another_php_file.php ,通过这条AJAX代码:
data:'theOption ='+ sel_stud ,
-
接收文件
another_php_file.php
:
$ selStudent = $ _POST ['theOption'];
-
Var $ selStudent(通过AJAX发布的用户选择)用于mysql搜索:
$ query =SELECT * FROM`类别`WHERE`master` = 0 AND`name` ='$ selStudent';
(当更改示例以适合您的数据库时,对$ selStudent的引用是除去。我们现在建立一个新的
< SELECT>
,然后在这里(这里,上面)使用它。 code>代码块,将HTML存储在名为
$ r
的变量中。当HTML完全构建完成后,我将定制代码简单回传给AJAX例程: echo $ r; 接收到的数据(自定义的
< SELECT>
代码块)为:code>
success:function(){// code block}
中我们可以使用它,我可以在这里将它注入到DOM中: $('#LaDIV')。html(whatigot);
另外,您现在可以看到第二个下拉控件按照第一个下拉控件的选项自定义。
像一个非微软浏览器。
I got a database table called category as shown:
I am trying to do a dynamic drop down box and the index script is shown as:
<?php
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `category`
WHERE `master` = 0";
$statement = $objDb->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Dependable dropdown menu</title>
<meta name="description" content="Dependable dropdown menu" />
<meta name="keywords" content="Dependable dropdown menu" />
<link href="/css/core.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="/js/core.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
</div>
</body>
</html>
The update.php is shown as:
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `category`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option
value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('',
$out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
The 2nd drop down box is not showing the values dependent on the 1st drop down box as shown:
Can someone help me please.
Here is an example that will do what you want. Essentially, you can use jQuery / AJAX to accomplish this.
I updated my example code to match your server login / table / field names, so if you copy/paste these two examples into files (call them tester.php
and another_php_file.php
) then you should have a fully working example to play with.
I modified my example below to create a second drop-down box, populated with the values found. If you follow the logic line by line, you will see it is actually quite simple. I left in several commented lines that, if uncommented (one at a time) will show you what the script is doing at each stage.
FILE 1 -- TESTER.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
FILE 2 - another_php_file.php
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$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
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT * FROM `category` WHERE `master` = 0";
$result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<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 student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</select><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
To answer your question in the comment: "How do you make the 2nd drop down box populate fields that are only relevant to a selected option from the 1st drop down box?"
A. Inside the .change
event for the first dropdown, you read the value of the first dropdown box:
$('#dropdown_id').change(function() {
var dd1 = $('#dropdown_id').val();
}
B. In your AJAX code for the above .change()
event, you include that variable in the data you are sending to the 2nd .PHP file (in our case, "another_php_file.php")
C. You use that passed-in variable in your mysql query, thereby limiting your results. These results are then passed back to the AJAX function and you can access them in the success:
portion of the AJAX function
D. In that success function, you inject code into the DOM with the revised SELECT values.
That is what I am doing in the example posted above:
The user chooses a student name, which fires the jQuery
.change()
selectorHere is the line where it grabs the option selected by the user:
var sel_stud = $(this).val();
This value is sent to
another_php_file.php
, via this line of the AJAX code:data: 'theOption=' + sel_stud,
The receiving file
another_php_file.php
receives the user's selection here:$selStudent = $_POST['theOption'];
Var $selStudent (the user's selection posted in via AJAX) is used in the mysql search:
$query = " SELECT * FROM `category` WHERE `master` = 0 AND `name` = '$selStudent' ";
(When changing the example to suit your database, the reference to $selStudent was removed. But this (here, above) is how you would use it).
We now build a new
<SELECT>
code block, storing the HTML in a variable called$r
. When the HTML is fully built, I return the customized code back to the AJAX routine simply by echoing it back:echo $r;
The received data (the customized
<SELECT>
code block) is available to us inside the AJAXsuccess: function() {//code block}
, and I can inject it into the DOM here:$('#LaDIV').html(whatigot);
And voila, you now see a second dropdown control customized with values specific to the choice from the first dropdown control.
Works like a non-Microsoft browser.
这篇关于动态下拉框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!