Ajax template engine underscore.js

Template engine

The JOSN data returned in the background will encounter a problem when rendering the page through JOSN data, that is, when JSON data renders the page, it will encounter the same format data problem (such as forms, lists... )

If you encounter content with similar data types, you can use templates for batch parsing of pages. Template engine is used at this time

Template engine: If we have a similar structure for display and the data is already there, the next step is to need a "model", so the model is a template engine in our professional terms

The template engine I used here is a third-party plugin underscore.js

underscorejs 官网

Here is a simple example

<script src="js/underscore.js"></script>
<body>
    <script>
        // 模板字符串
        var templateStr = "大家好,我是<%=name%>,今年<%=age%>岁了,我来自美丽的<%=adress%>,我很喜欢<%=hobby%>";
        // 模板编译函数
        var compiled = _.template(templateStr);
        //console.log(compiled)
        // JOSN数据
        var jsonObj1 = {
            "name": "小黑",
            "age": "25",
            "adress": "三亚",
            "hobby": "冲浪"
        }
        var jsonObj2 = {
            "name": "小白",
            "age": "22",
            "adress": "冰城哈尔滨",
            "hobby": "冰雪运动"
        }
        // 编译后的结果
        var result1 = compiled(jsonObj1);
        var result2 = compiled(jsonObj2);
        console.log(result1);
        console.log(result2);
    </script>
</body>

 underscore.js table rendering

There are two ways to make a template

The first is to directly make the template HTML code into a string and then make a template function

var template = "<tr><td><%=id%></td><td><%=name%></td><td><%=age%></td><td><%=sex%></td></tr>"

The second is to achieve through our script tag

If the type value of script is "text/javascript;", the internal code will be recognized and executed, but if it is not, it will be silent and will not run without error, so it can be used to store some content

For example, you can set the type value of the following template to "text/template" to indicate that the template string is stored inside, or you can set other ones, try to set meaningful names

<body>
    <table>
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
    </table>
    <script type="text/template" id="templateText">
        <tr>
      <td><%=id%></td>
      <td><%=name%></td>
      <td><%=age%></td>
      <td><%=sex%></td>
    </tr>
  </script>
    <script src="js/underscore.js"></script>
    <script>
        var table = document.getElementsByTagName("table")[0];
        // 获取模板结构
        var templateText = document.getElementById("templateText");
        // 获取template内部的数据
        var templateData = templateText.innerHTML;
        // 发送请求
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                    var data = xhr.responseText;
                    var obj = JSON.parse(data)
                    renderDom(obj)
                }
            }
        }
        xhr.open("get", "test.json", true);
        xhr.send(null);
        // 渲染模板
        function renderDom(obj) {
            // 编译模板函数
            var compiled = _.template(templateData);
            // 遍历返回的数据内容
            _.each(obj.info, function (item) {
                var dom = compiled(item);
                // 追加节点上树
                table.innerHTML += dom;
            })
        }
    </script>
</body>

.json

{
  "info": [
    {
      "id":10001,
      "name": "小明",
      "age": 18,
      "sex": "男"
    },
    {
      "id":10002,
      "name": "小兰",
      "age": 15,
      "sex": "男"
    },
    {
      "id":10003,
      "name": "小红",
      "age": 14,
      "sex": "男"
    }
  ]
}

Guess you like

Origin blog.csdn.net/weixin_41040445/article/details/114977777