效果圖
html
html只用兩個簡單的select選擇框。
js
js代碼就是在頁面加載完第一次請求後臺PHP代碼得到第一個選項的子分類,而後每當分類改變時,再次請求後臺得到具體的子分類。
PHP
前臺請求後臺的PHP,得到數據進行返回,而PHP的數據大多數是從數據庫中得到的,在這裏只是一些僞數據
源代碼
html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.content{
width: 100%;
text-align: center;
margin-top: 50px;
}
.cate{
width: 150px;
height: 30px;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="content">
<select class="cate" name="cate" id="cate">
<option value="0">水果</option>
<option value="1">電子商品</option>
<option value="2">服裝</option>
</select>
<select class="cate" name="attr" id="attr">
</select>
</div>
</body>
<script src="./js/jquery.min.js"></script>
<script>
$(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("<option value=" + data[i]['id'] + ">"
+ data[i]['name'] + "</option>");
}
}
});
}
</script>
</html>
PHP
<?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]);