欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

handlebars获取json数据(Map对象(与集合处理一样))

程序员文章站 2024-01-30 21:51:52
...
    @RequestMapping("testDemo05.do")
    public Map<String , Emp> testDemo05(){
        Map<String , Emp> map = new HashMap<String , Emp>();
        Emp emp1 = new Emp(1111, "老龚", 33, "1", 1000.00, new Date(), new Timestamp(System.currentTimeMillis()));
        Emp emp2 = new Emp(1111, "老李", 30, "0", 1600.00, new Date(), new Timestamp(System.currentTimeMillis()));
        map.put("emp1", emp1);
        map.put("emp2", emp2);
        return map;
    }
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width="50%" border="1">
    <thead>
        <tr>
            <th>NO.</th>
            <th>ID</th>
            <th>NAME</th>
            <th>AGE</th>
            <th>GENDER</th>
            <th>SALARY</th>
            <th>BIRTHDAY</th>
            <th>HIREDATE</th>
        </tr>
    </thead>
    <tbody id="demo">

    </tbody>
</table>



<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/handlebars-4.0.10.min.js"></script>

<!-- 定义handlebars模板 -->
<script type="text/x-handlebars-template" id="demo_ht">
    {{#each this}}
        <tr>
            <td>{{myCount @index}}</td>
            <td>{{id}}</td>
            <td>{{name}}</td>
            <td>{{gender}}</td>
            <td>{{age}}</td>
            <td>{{salary}}</td>
            <td>{{birthday}}</td>
            <td>{{hiredate}}</td>
        </tr>
    {{/each}}
</script>
<script type="text/javascript">
    $(function(){
        $.ajax({
            type:"post",
            url:"test/testDemo05.do",
            dataType:"json",
            success:function(data){
                //编译模板
                var demo_ht = Handlebars.compile($("#demo_ht").html());

                //定义一个helper 实现在index基础上从1开始
                Handlebars.registerHelper("myCount" , function(index){
                    return index + 1 ;
                });

                //模板渲染数据
                var _html = demo_ht(data);
                //dom操作
                $("#demo").html(_html);
            },
            error:function(){
                alert("请求发生异常!");
            }
        });
    });
</script>
</body>
</html>