Javascript 在循环内循环以获取 JSON

标签 javascript html json loops

我想列出类别,并且在每个类别中我想列出子类别,所以我在这样的循环中运行循环,但不幸的是它像这样返回我:

Category(Mobile)
Category(Laptop)
Subcategory(Iphone4)
Subcategory(Iphone5)
Subcategory(Iphone6)
Subcategory(dell1)
Subcategory(dell2)
Subcategory(dell3)

但我想要的是一些这样的想法:

Category(Mobile)
Subcategory(Iphone4)
Subcategory(Iphone5)
Subcategory(Iphone6)
Category(Laptop)
Subcategory(dell1)
Subcategory(dell2)
Subcategory(dell3)

这是我的代码:

$(document).ready(function()
         {
              var url="https://myjson";
              $.getJSON(url,function(result){
                   $.each(result, function(i, field){
                        var categoryId=field.categoryId;
                        var categoryName=field.categoryName;
                        $("#listview").append("<h3>"+ categoryName + "</h3>");
                        $.each(field.subcategories, function(i, row){
                             var id=row.subCategoryId;
                             var subCategoryName=row.subCategoryName;
                             $("#listviewchild").append("<p>"+ subCategoryName + "</p>");
                        });
                   });
              });
         });
   <div class="container-fluid">
    
     <div id="listview">
     </div>
     <div id='listviewchild'>
     </div>
    </div>

最佳答案

基本上,从您的代码中,您的类别将始终根据您拥有的 html 附加到子类别的上方。

这是将根据您的需要附加的逻辑

JavaScript

 $(document).ready(function()
         {
              var url="https://myjson";
              $.getJSON(url,function(result){
                   $.each(result, function(i, field){
                        var categoryId=field.categoryId;
                        var categoryName=field.categoryName;
                        $("#listview").append("<h3>"+ categoryName + "</h3>");
                        $.each(field.subcategories, function(i, row){
                             var id=row.subCategoryId;
                             var subCategoryName=row.subCategoryName;
                             $("#listview").append("<p>"+ subCategoryName + "</p>");
                        });
                   });
              });
         });

html

   <div class="container-fluid">

     <div id="listview">
     </div>
    </div>

关于Javascript 在循环内循环以获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090522/

相关文章:

javascript - Bootstrap 4 可折叠卡片 - 断断续续的动画

javascript - 在单页 MEAN 应用程序中优雅地隐藏导航栏。

php - 如何更改php中 'echo'的位置?

HTML 选择选项,文本格式

android - 将 AsyncTask 与来自数据库的 JSON 请求一起使用

json - 使用 Play 框架在 Scala 中解析 Json 字符串

javascript - 如何使用 JavaScript 拆分此字符串?

Javascript异步赋值和回调

html - 获得一个正确的方法来设计复选框,而不是后面跟着标签标签

python - 确保 POST 数据是有效的 JSON