数据JSON格式

代码
- html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Documenttitle>
- head>
-
- <body>
- <select name="" id="cateOne">
- select>
- <select name="" id="cateTwo">
- select>
- <select name="" id="cateThree">
- select>
- <script src="https://code.jquery.com/jquery-1.12.4.min.js">script>
- <script>
- var cateOption = []// 初始化一个空数组用于存储所有分类的子分类数据
- $(document).ready(function () {
- var optionOneId;
- // 渲染一级分类数据
- function renderCate() {
- //获取select元素
- var $select = $('#cateOne');
- // 遍历
- $.each(cateOption, function (index, cate) {
- var $option = $(")
- .val(cate.categoryId)
- .text(cate.categoryName);
- $select.append($option)
- });
- $select.val(cateOption[0].categoryId);
- getCateTwoData(0)//获取对应二级分类
- }
- // 根据一级分类ID获取对应的二级分类数据
- function getCateTwoData(optionOneId) {
- cateTwoData = cateOption[optionOneId].categoryChild
- // console.log(cateTwoData);
- renderCateTwo(cateTwoData);
- }
- //渲染二级分类数据
- function renderCateTwo(cateTwoData) {
- var $select = $('#cateTwo');
- // 清空之前的二级分类选项
- $select.empty();
-
- // 遍历二级分类数据并渲染到#cateTwo中
- $.each(cateTwoData, function (index, cate) {
- // console.log(index, 'idnex');
- var $option = $(")
- .val(cate.categoryId)
- .text(cate.categoryName);
- $select.append($option);
- });
- //默认选中第一个二级分类
- $select.val(cateTwoData[0].categoryId);
- getCateThreeData(0)
- }
-
- // 根据二级分类ID获取对应的三级分类数据
- function getCateThreeData(optionTwoIndex) {
- var cateThreeData = cateTwoData[optionTwoIndex].categoryChild
- // console.log(cateThreeData,'cateThreeDatacateThreeDatacateThreeData');
- rendercateThree(cateThreeData);
- }
-
- function rendercateThree(cateThreeData) {
- var $select = $('#cateThree');
- // 清空之前的二级分类选项
- $select.empty();
-
- // 遍历二级分类数据并渲染到#cateTwo中
- $.each(cateThreeData, function (index, cate) {
- // console.log(index, 'idnex');
- var $option = $(")
- .val(cate.categoryId)
- .text(cate.categoryName);
- $select.append($option);
- });
- }
-
- $.ajax({
- url: 'http://sph-h5-api.atguigu.cn/api/product/getBaseCategoryList',
- type: 'get',
- dataType: 'json', // 假设返回的是 JSON 数据
- success: function (res) {
- console.log(res.data);
- cateOption = res.data;
- renderCate();
- }
- })
- // 获取点击一级分类option的id
- $('#cateOne').on('change', function () {
- var optionOneId = $(this).prop('selectedIndex');
- getCateTwoData(optionOneId)
- })
- // 获取点击二级分类option的id
- $('#cateTwo').on('change', function () {
- var optionTwoIndex = $(this).prop('selectedIndex');
- console.log(optionTwoIndex);
- getCateThreeData(optionTwoIndex)
- })
- });
- script>
- body>
-
- html>
页面展示:

备注:仅练习,没有优化,如果有更简洁的代码可以讨论