如何使用Jquery,Ajax,PHP和Mysql进行动态相关选择框。当在“父”框中进行选择时,从属选择框允许刷新“子”框列表数据。在这篇文章中,我给出了“catergory”和“subcategory”之间的数据库关系示例。这是非常简单的jquery代码,希望大家喜欢。
数据库
示例数据库表。Data包含列表框的完整数据,data_parent的key关系与Data包含父子关系。
CREATE TABLE 'data'
(
'id' int primary key auto_increment,
'data' varchar(50),
'weight' int(2),
);
CREATE TABLE `data_parent`
(
`pid` int(11) primary key auto_increment,
`did` int(11) unique,
`parent` int(11),
Foreign key(did) references data(id)
)
sections_demo.php
包含javascipt和PHP代码。$(“。country”)。change(function(){} - country是select box的类名。使用$(this).val()调用select box值.PHP代码显示Data中的结果,其中weight =' 1'
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
//HTML Code
Country :
<select name="country" class="country">
<option selected="selected">--Select Country--</option>
<?php
include('db.php');
$sql=mysql_query("select id,data from data where weight='1'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';
} ?>
</select> <br/><br/>
City :
<select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
ajax_city.php
包含PHP代码。显示data和date_parent表的结果
<?php
include('db.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select b.id,b.data from data_parent a,data b where b.id=a.did and parent='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>