JSON对象的动态UI [英] Dynamic UI from JSON object
问题描述
我正在尝试找到一种将动态JSON对象转换为有效HTML网页的方法.这个想法是为了能够将需要从IoT设备显示的内容推送到云中,并使用户能够输入和保存配置.
I'm trying to find a way to translate a dynamic JSON object into a valid HTML webpage. The idea is to be able to push up what did needs to be displayed from an IoT device into the cloud and have the user be able to input and save the configuration.
json看起来像这样
The json would look something like this
{
"loginConfiguration": {
"username": "string",
"password": "string",
"hostname": "string"
},
"systemConfiguration": {
"numberOfEvents": "int"
}
}
理想的输出将是3个带有字符串输入的文本框,位于一个名为loginConfiguration的部分下,然后是另一个具有1个整数输入的部分.但是请注意,json对象会有所不同,并且应该能够容纳该对象.
And the ideal output would be 3 text boxes with string inputs under a section called loginConfiguration and then another section with 1 integer input. But please note that the json object would differ and should be able to accommodate for that.
我愿意接受技术堆栈,但是使用javascript/jQuery似乎是最有可能的.如果您有专门为此制作的Dart之类的替代产品,请说明如何实现.
I'm open to technology stacks, but it seems to be the most possible with javascript/jQuery. If you have an alternative like Dart that is made for this then please show how this could be accomplished.
推荐答案
我希望您能理解我的代码,并且我已经使它尽可能地具有动态性,对于json您需要知道的唯一元素是初始对象.例如,我曾经使用过:
I hope you will understand my code , and that i have made it as dynamic as posible , only element you need to know for json is inital object. For example i have used :
var json =
'{
"result" : {
"loginConfiguration" : {
"username" : "string",
"password" : "string",
"hostname" : "string"
},
"systemConfiguration" : {
"numberOfEvents" : "int"
}
}
}'
这是jsFiddle: https://jsfiddle.net/22dx9u7d/
Here is 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)
}
})
这篇关于JSON对象的动态UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!