Ajax 获取json数据 如何处理,并使用Handlebars 编译到HTML


Html:


 <tbody id="points-m">
    </tbody>

使用:Handlebars


 <script id="points-template" type="text/x-handlebars-template">
{{#each points}}
<tr>
    <td>{{points-time}}</td>
    <td class="c-org">{{points-number}}</td>
    <td>{{points-desc}}</td>
</tr>
{{/each}}
</script>

javascript:


 <script type="text/javascript">
    $(document).ready(function () {
    var key = getcookie('key');
    if (key == '') {
        var urlarray = geturlstring();
        if (urlarray['key']) {
            key = urlarray['key'];
        } else {
            location.href = 'login.html';
        }
    }

    $.ajax({
        type: 'post',
        url: ApiUrl + "/index.php?act=member_points",
        data: {key: key},
        dataType: 'json',
        success: function (data) {
            $.each(data, function (i, item) {

            })
        }
    });
    var template = Handlebars.compile($('#points-template').html());
    $('#points-m').html(template(points_list));
    })
</script>

现在的问题是怎么把获取到的数据转换为这种形式


 var points_list = {
    points:[
        { pl_addtime: "2014-10-22", pl_number: "1000", pl_desc: "1234567890" },
        { pl_addtime: "2014-10-22", pl_number: "1000", pl_desc: "1234567890" },
        { pl_addtime: "2014-10-22", pl_number: "1000", pl_desc: "1234567890" }
   ]};

console.log(data)获取的数据是这样的
图片描述

json handlebars Ajax

名字就是⑨ 10 years, 2 months ago

 var template = Handlebars.compile($('#points-template').html());

$.ajax({
    type: 'post',
    url: ApiUrl + "/index.php?act=member_points",
    data: {key: key},
    dataType: 'json',
    success: function (data) {
        var points_list={points:data.datas.points_list};
        $('#points-m').html(template(points_list));
    }
});

凉风吹过de夜 answered 10 years, 2 months ago

不知道你的 pl_number和 pl_desc`是啥,你看着改吧。


 $.ajax({
    type: 'post',
    url: ApiUrl + "/index.php?act=member_points",
    data: {key: key},
    dataType: 'json',
    success: function(data) {
        var points = data.datas.points_list.map(function(i,v) {
                return {
                    pl_addtime: (new Date(+v.pl_addtime*1000)).toLocaleDateString().split('/').join('-'),
                    pl_number: v.pl_id,
                    pl_desc: v.pl_memberid
                };
            });
        var points_list = { points: points };
        var template = Handlebars.compile($('#points-template').html());
        $('#points-m').html(template(points_list));
     }
});

ID从来不亮 answered 10 years, 2 months ago

Your Answer