将json对象转换为HTML的最佳解决方案

时间:2014-01-21 19:55:50

标签: javascript jquery html json javascript-objects

我的HTML页面主要显示从服务器检索的页面列表。

我选择实现这部分分为两部分

  1. 在没有带微调器的页面列表的情况下渲染页面。

  2. 加载页面后,我正在进行AJAX调用以将页面列表检索为JSON

  3. 我使用jQuery作为我的javascript库

  4. 我通过AJAX获取JSON,我需要将其转换为HTML并相应地显示在页面中。

    之前我没有做过类似的翻译,所以我想知道将JSON转换为html的最佳方法是什么。

    我做了一些研究。我可以看到使用一些库或迭代每个元素并构造div。

    哪个更好?

    我的JSON示例就像

    {
        "SomeID": 12345,
        "someName": "somefile",
        "totalPageNum": 5,
        "pages": [ //Array of pages
            {
                "pageFields": [ // Array of page fields
                    {
                        "field": {
                            "id": 1,
                            "type": "someType",
                            "name": "someFieldName",
                            "value": "Some Field Value"
                        },
                        "coordinates": {
                            "x": 105,
                            "y": 543
                        }
                    }
                ],
                "somePagenumber": "1",
                "somePageURLurl": "/location/to/page1"
            }
        ]
    }
    

    感谢阅读!!!

2 个答案:

答案 0 :(得分:4)

术语“最佳解决方案”是有偏见的。 什么是肯定的好解决方案:使用JQuery来做到这一点。

示例:

<!-- Include JQuery, only one time in the page header -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
$.getJSON("/admin/json/endpoint",function(data) {         
  $.each(data.collection, function(i,e) {
  var lmod = formatDate(new Date(e["lmodified"]));
  var row = "<tr><td>"+e["name"]+"</td><td>"+lmod+"</td>"
  $("#dpub tr:first").after(row);
  });
});
</script>

<table id="dpub" style="width:100%;">
 <tr>
   <th style="width:20%;">Name</th>
   <th>Last modified</th>
 </tr>
</table>

请参阅:http://api.jquery.com/jquery.getjson/

console.log(data)可以帮助您了解javascript中返回对象的结构。打开浏览器javascript控制台以查看内容。

当事情变得复杂并且您不仅想要向表中添加简单行时,请考虑使用模板引擎,如mustache.js

答案 1 :(得分:1)

您可以通过迭代每个元素并使用字符串连接(如您所述)在JavaScript中将HTML构建为字符串。

您还可以使用轻量级JavaScript模板系统来实现更清晰的代码。我建议使用mustache.js

无论哪种方式,最终你都会使用类似jQuery's .html()的内容插入实际页面。