如何从Json创建HTML表单

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从Json创建HTML表单相关的知识,希望对你有一定的参考价值。

我正在使用Activiti,我有一个这样的表格:

enter image description here

当我使用Rest API时,该表单将与Json一起返回,如下所示:

{
    "formKey": null,
    "deploymentId": "21151",
    "processDefinitionId": null,
    "processDefinitionUrl": null,
    "taskId": "21159",
    "taskUrl": "http://localhost:8080/activiti-rest/service/runtime/tasks/21159",
    "formProperties": [
        {
            "id": "firstName",
            "name": "First Name",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": true,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "lastName",
            "name": "Last Name",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "phoneNumber",
            "name": "Phone Number",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "dateTime",
            "name": "Date Time",
            "type": "date",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": "dd/MM/yyyy",
            "enumValues": []
        },
        {
            "id": "city",
            "name": "City",
            "type": "enum",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": [
                {
                    "id": "0",
                    "name": "TPHCM"
                },
                {
                    "id": "1",
                    "name": "HN"
                }
            ]
        }
    ]
}

我想将这个Json转换成一个html表单,其中包含Json结果中的输入。我搜索了很多关于使用库的帖子,但是我不能像我所需要的那样使我的Json结果。所以任何方式这样做? 非常感谢你!

答案
    **Store your json response in a variable.eg:var json;**
As the json is getting from a Rest API,it can be stored in a variable.So that we can use that to proceed the form creation.We can iterate the formProperties to create the form inputs.
    <!DOCTYPE html>
    <html>
    <body>
    <form id="form">
      <input type="submit" name="mysubmit" value="Submit" />
    </form>


    <script>
    var formData = json.formProperties;
    var inputs = '';
     for (var i = 0; i < formData.length; i++) {
        if(formData[i].id == 'city'){
        inputs += '<label>'+formData[i].id+'</label></br><select><option>'+formData[i].enumValues[0].name+'</option><option>'+formData[i].enumValues[1].name+'</option> </select>'+'</br></br>';
        }else if(formData[i].id == 'dateTime'){
        inputs += '<label>'+formData[i].id+'</label></br><input type="date"/>'+'</br></br>';
        }else{
       inputs += '<label>'+formData[i].id+'</label></br><input  type="text" value="" id="' + formData[i].id + '">'+'</br></br>';
       }
     }
     document.getElementById('form').insertAdjacentHTML('afterbegin', inputs);
    </script>

    </body>
    </html>
另一答案

首先是评论,你真的应该在你的问题中展示你到目前为止所尝试的内容,并详细说明你遇到的具体问题。

此技术使用DOM对象来创建表单。它使用文档片段来限制DOM的实际更新次数。希望代码中的注释是自我解释的。

//Just for demo purposes - this would be your API Call
var data = getData();

//Get the bit we need
var formData = data.formProperties;

//Call our function to carete the form
createForm(formData);

//The magic
function createForm(data){
  //Create a fragment so we aren't constantly updating the DOM
  var container = document.createDocumentFragment();
  
  data.forEach(function(formProp){
  //Create a row div with a class
  var rowDiv = document.createElement("div");
  rowDiv.classList.add("rowDiv");
  
  //Create a label
  var label = document.createElement("label");
  label.setAttribute("for", formProp.id);
  label.innerHTML = formProp.name;
  
  //Create a form element
  var formElement = document.createElement(formProp.type == "enum" ? "select" : "input");
  //Set it's properties
  formElement.id = formProp.id;
  formElement.name = formProp.id;
  formElement.required = formProp.required;
  formElement.readOnly = !formProp.writable;
  
  
  //Do some stuff if the form element is required
  if(formProp.required){
    rowDiv.classList.add("required");    
  }
  
  //Do stuf for not select 
  if(formProp.type != "enum"){
    formElement.value = formProp.value;
    
    if(formProp.type == "date") {
      formElement.type = "date";
    }
    //Add any other types here
    else {
      //falback to text
      formElement.type = "text";
    }
  }
  //Add the enum values
  else {
    formProp.enumValues.forEach(function(formEnum){
      var opt = document.createElement("option");
      opt.value = formEnum.id;
      opt.text = formEnum.name;   
      opt.selected = formEnum.id == formProp.value;
      formElement.appendChild(opt);
    });    
  }
  
  //Add label and element to div
  rowDiv.append(label);
  rowDiv.append(formElement);  
  
  //Apend div to fragment
  container.appendChild(rowDiv);
  });
  //Add fragment to form
  document.getElementById("mainForm").appendChild(container);
}



function getData(){
var data = {
    "formKey": null,
    "deploymentId": "21151",
    "processDefinitionId": null,
    "processDefinitionUrl": null,
    "taskId": "21159",
    "taskUrl": "http://localhost:8080/activiti-rest/service/runtime/tasks/21159",
    "formProperties": [
        {
            "id": "firstName",
            "name": "First Name",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": true,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "lastName",
            "name": "Last Name",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "phoneNumber",
            "name": "Phone Number",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "dateTime",
            "name": "Date Time",
            "type": "date",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": "dd/MM/yyyy",
            "enumValues": []
        },
        {
            "id": "city",
            "name": "City",
            "type": "enum",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": [
                {
                    "id": "0",
                    "name": "TPHCM"
                },
                {
                    "id": "1",
                    "name": "HN"
                }
            ]
        }
    ]
}
return data;
};
/*Add some styling for required*/
.required::after {
  content: " *";
  color:#F00;
}

.rowDiv {
  padding:2px;
}

.rowDiv label {
  display:inline-block;
  width: 20%;
}
<form id="form">
  <fieldset id="mainForm">
  </fieldset>
  <fieldset id="buttons">
  <input type="submit" value="Complete Task">
  <input type="reset" value="Reset From">
  </fieldset>
</form>

以上是关于如何从Json创建HTML表单的主要内容,如果未能解决你的问题,请参考以下文章

从viewPager片段(Kotlin)中获取用户输入信息

如何创建片段以重复变量编号中的代码行

如何创建动态 html 表单的 JSON 对象(表单元素)?

如何使用 JSON 定义创建 html 表单?

使用 Angularjs 和 Nodejs 从 HTML 表单另存为 JSON 文件

如何从具有相同名称的字段的表单创建 JSON 文件?