image
html
html只用两个简单的select选择框。
image
js
js代码就是在页面加载完第一次请求后台PHP代码得到第一个选项的子分类,而后每当分类改变时,再次请求后台得到具体的子分类。
image
PHP
前台请求后台的PHP,得到数据进行返回,而PHP的数据大多数是从数据库中得到的,在这里只是一些伪数据
image
源代码
html
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
Document.content{
width: 100%;
text-align: center;
margin-top: 50px;
}
.cate{
width: 150px;
height: 30px;
border-radius: 5px;
}
水果
电子商品
服装
$(document).ready(function(){
getDataForAjax();
});
$("#cate").change(function () {
getDataForAjax();
});
function getDataForAjax() {
cate_id = $('#cate').val();
$.ajax({
type:"post",
url:"data.php",
dataType:'json',
data:{
cate_id:cate_id
},
success:function (data) {
console.log(data);
$('#attr').empty();
for(var i = 0;i < data.length;i++){
$('#attr').append(""
+ data[i]['name'] + "");
}
}
});
}
PHP
$category = $_POST['cate_id'];
//得到分类ID,查询数据库,得到分类下有哪些子分类,在这里只是伪数据。
$data = [
[
['id' => 1,'name' => '苹果'],
['id' => 2,'name' => '香蕉'],
['id' => 3,'name' => '橘子'],
['id' => 4,'name' => '梨'],
],
[
['id' => 1,'name' => '手机'],
['id' => 2,'name' => '电脑'],
['id' => 3,'name' => '平板'],
['id' => 4,'name' => '手表'],
],
[
['id' => 1,'name' => '上衣'],
['id' => 2,'name' => '裤子'],
['id' => 3,'name' => '鞋子'],
],
];
//进行json转换,返回数据。
echo json_encode($data[$category]);
代码文件