HTML网页定义
<html>
<meta http-equiv="Content-Type" content="text/html; charset=U">




















HomeWeb Front-endHTML TutorialNested JSON data automatically writes back to HTML web pages_html/css_WEB-ITnose

This article introduces the solution and technical implementation code for parsing JSON nested strings from the MongoDB database and displaying data content according to custom attributes of HTML interface elements.

HTML web page definition
<html><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><head></head><body><h1 id="表单展示数据回写测试-JavaScript">表单展示数据回写测试 JavaScript</h1><p id="demo" >这是表单数据解析示例.</p><div> <label >名称:</label><label fieldid="name"></label><br>通过自定义属性“fieldtype”来定义数据类型。<br><br><button id="test" type="button" onclick="showAllElem()">测试展示表单数据</button><br><br><label>标题:</label><label fieldid="title"></label><br><label >年龄:</label><label fildid="old"></label><br>多行子表单,字段属性定义为“subid”,表单按数据字段属性定义,标识出含有子表,属性为“subtable”单独定义列数,其他不变。<table id="dynamictable" fieldid="subdatas" subtable="3" border="1" cellspacing="0" width="400"><tr><td>数据名称</td><td>数据类型</td><td>数值</td></tr><tr><td><label subid="fieldid"></label></td><td><label subid="fieldtype"></label></td><td><label subid="fieldvalue"></label></td></tr></table><br><label >结束标志:</label><label fieldid="flag"></label><br></div> </body></html>

Note, the form definition rules are as follows:
(1) Use Label to echo page data;
(2) In label, customize Attribute "fieldid", if it is a table, distinguish the custom attribute as "subid";
(3) In the element of table

, add the custom attribute subtable, whose attribute value is the column of the table number.

When designing the page, the definition of multi-line subforms must be designed according to rules. The requirements are as follows:

  • A header row is required;
  • Define a row of data in advance.
  • JavaScript code
    <script>//表单增加插入一行function insertRow(){  var dytb_id = 'dynamictable';  var dy_row_num = document.getElementById(dytb_id).rows.length;  //取table中第二行单元格集合  var dy_row = document.getElementById(dytb_id).rows[1].cells;  //在table末尾,追加一行  var dytb=document.getElementById(dytb_id).insertRow(dy_row_num);  for (i = 0;i<dy_row.length; i++){    var dy_td = dytb.insertCell(i);    dy_td.innerHTML = dy_row[i].innerHTML;     } }//显示所有回写数据function showAllElem(){    var elems = document.getElementsByTagName("*");  //遍历所有元素    var ret_json = "";  //定义返回JSON数据字符串    var m = 0;          //JSON嵌套子文档起点    var subcolumns = 0;  //多行表单列数    var subrows = 0;     //多行表单数据行数    var row_num = 0;     //数据行数    ret_json = "{\"name\":\"测试JSON\",\"title\":\"测试标题\",\"subtable\":[{\"fieldid\":\"数据名称a\",\"fieldtype\":\"string\"},{\"fieldid\":\"数据名称b\",\"fieldtype\":\"number\"},{\"fieldid\":\"数据名称c\",\"fieldtype\":\"datetime\"}],\"flag\":\"测试结束!\"}";       //将 JavaScript 对象表示法 (JSON) 字符串转换为对象。    json_obj = JSON.parse(ret_json);    for(var i=0;i<elems.length;i++){        if (elems[i].hasAttribute("fieldid") && !(elems[i].hasAttribute("subtable"))){            //按键值获取对象的值            var tmp_key = elems[i].getAttribute("fieldid");            alert(tmp_key);            elems[i].innerText = json_obj[tmp_key];            //n++;        }else{            if (elems[i].hasAttribute("subtable")){                subcolumns = elems[i].getAttribute("subtable");                var tbl_id = elems[i].id;                //取表单数据行数                subrows = document.getElementById(tbl_id).rows.length - 1;                //按规则取多行子表单数据                var json_obj_dim = json_obj["subtable"];                for (var j=subrows;j<json_obj_dim.length;j++){                    insertRow();                }                m = 0;            }else{                if (elems[i].hasAttribute("subid") && (m < subcolumns)){                    var tmp_key = elems[i].getAttribute("subid");                    alert(tmp_key);                    elems[i].innerText = json_obj_dim[row_num][tmp_key];                    m++;                }else{                    if (elems[i].hasAttribute("subid")){                        //多行子表单数据换行                        row_num++;                        var tmp_key = elems[i].getAttribute("subid");                        alert(tmp_key);                        elems[i].innerText = json_obj_dim[row_num][tmp_key];                                                m = 1;                      }                }            }        }    } }</script>

    The JSON data content and format are as follows:

    {"name":"测试JSON","title":"测试标题","subtable":[ {"fieldid":"数据名称a","fieldtype":"string"}, {"fieldid":"数据名称b","fieldtype":"number"}, {"fieldid":"数据名称c","fieldtype":"datetime"} ],"flag":"测试结束!"}"

    According to the system design, this JSON data is BSON data taken out from the MongoDB database through Webservice. The "key" of the "key-value" pair in the data corresponds to the custom attribute "fieldid" or "subid" of label on the HTML web page.

    The following sequence diagram shows a concise principle of processing JSON data, in which the process and content of reading the MongoDB database are omitted.

    Created with Raphaël 2.1.2 Browser Browser HTML page HTML page JS function JS function MongoDB MongoDB JSON object JSON object design page, custom attribute () Get JSON data () Read BSON data () Traverse HTML interface element () parse (JSON string) Get the value of the JSON object according to the interface element key value ()

    Note: JSON is supported in the following document modes: Internet Explorer 8 standards mode, Internet Explorer 9 Standards mode, Internet Explorer 10 Standards mode, Internet Explorer 11 Standards mode. Also supported in Store apps (Windows 8 and Windows Phone 8.1).
    Not supported in the following document modes: Quirks, Internet Explorer 6 Standards Mode, Internet Explorer 7 Standards Mode.

    Reference:
    Web form document design and technical implementation Xiao Yongwei 2015.5
    JavaScript traverses HTML form elements and form definition Xiao Yongwei 2015.5
    W3School provides content: http://www.w3school.com. cn/jsref/dom_obj_document.asp
    Provided by Microsoft: JSON.parse function (JavaScript)

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

    HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

    How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

    TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

    HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

    HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

    How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

    ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

    HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

    The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

    Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

    HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

    Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

    A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

    How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

    Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor