使用Jquery和Ajax的动态依赖选择框
如何使用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
()
{
$(".country").change( function()
{
var id=$( this).val();
vardataString = 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">
<?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 ;
} ?> City : <select name="city" class=" city">
</select>
ajax_city.php 包含PHP代码。 显示 data 和 date_parent 表的结果
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 ;
}
}
?>扫一扫,关注我们