温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Jquery和Ajax的动态依赖选择框

发布时间:2020-08-05 09:12:29 来源:ITPUB博客 阅读:105 作者:cenfeng 栏目:web开发

如何使用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>';
}
}
?>


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI