【问题标题】:Dynamic UI from JSON object来自 JSON 对象的动态 UI
【发布时间】:2020-08-28 00:21:48
【问题描述】:

我正在尝试找到一种将动态 JSON 对象转换为有效 HTML 网页的方法。这个想法是能够将需要显示的内容从 IoT 设备推送到云中,并让用户能够输入和保存配置。

json 看起来像这样

{
  "loginConfiguration": {
    "username": "string",
    "password": "string",
    "hostname": "string"
  },
  "systemConfiguration": {
    "numberOfEvents": "int"
  }
}

理想的输出是在名为 loginConfiguration 的部分下带有字符串输入的 3 个文本框,然后是带有 1 个整数输入的另一个部分。但请注意,json 对象会有所不同,应该能够适应这种情况。

我对技术堆栈持开放态度,但它似乎是最有可能使用 javascript/jQuery 的。如果您有类似 Dart 之类的替代方案,请说明如何实现。

【问题讨论】:

    标签: json


    【解决方案1】:

    我希望你能理解我的代码,并且我已经让它尽可能动态,只有你需要知道的 json 元素是初始对象。例如我用过:

    var json = 
    '{
        "result" : {
            "loginConfiguration" : {
                "username" : "string",
                "password" : "string",
                "hostname" : "string"
            },
            "systemConfiguration" : {
                "numberOfEvents" : "int"
            }
        }
    }'
    

    这里是 jsFiddle:https://jsfiddle.net/22dx9u7d/

    这里是jquery代码

    var sectionHtml = ""
    var controlHtml = ""
    var data = JSON.parse(json) 
    
    $(data.result).each(function(index,value){ 
    
        //Counts how many sections there are
        var countSections = Object.keys(this).length;
        var i = 0
      
        //Goes through sections 
        while(i != countSections){   
            var sectionName = Object.keys(this)[i]
            sectionHtml = "<div id='"+ sectionName +"'><h1>Section:"+ sectionName +"</h1>"
    
             //Goes through sections
            $(data.result[Object.keys(this)[i]]).each(function (index, value) {
                     
                //Count controls inside section
                var countControls = Object.keys(this).length
                var j = 0
    
                //For each control take data needed
                while(j != countControls){    
                    var controlName = Object.keys(this)[j]
                    var controlType = value[controlName] 
    
                    //Do your checking  for control type and generate html
                    if (controlType == 'string'){
                        sectionHtml += '<label>'+ controlName +' : </label><input type="text" id="'+ controlName +'" /><br />'
                    } else if (controlType == 'int'){
                        sectionHtml += '<label>'+ controlName +' : </label><input type="number" id="'+ controlName +'" /><br />'
                    }
                    j++
                }
     
            }); 
            i++
    
            //Close section html
            sectionHtml += "</div>"
            //Append it to html 
            $("#appendDiv").append(sectionHtml)
        }  
     
    })
    

    【讨论】:

      猜你喜欢
      • 2016-09-09
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多