车把没有为JSON响应正确填充模板

时间:2016-05-04 21:00:45

标签: javascript json handlebars.js

您好我正在进行http调用mvc控制器操作,该操作返回JSON,如下所示:

[
    {
        "PlanCode": "P001 ",
        "PlanName": "Plan1 "
    },
    {
        "PlanCode": "P002$ ",
        "PlanName": "Plan2$ "
    },
    {
        "PlanCode": "P003$ ",
        "PlanName": "Plan3$ "
    },
    {
        "PlanCode": "P004$ ",
        "PlanName": "Plan4$ "
    },
    {
        "PlanCode": "P005$ ",
        "PlanName": "Plan5$ "
    },
    {
        "PlanCode": "P006$ ",
        "PlanName": "Plan6$ "
    },
    {
        "PlanCode": "P007$ ",
        "PlanName": "Plan7$ "
    },
    {
        "PlanCode": "P007$ ",
        "PlanName": "Plan7$ "
    },
    {
        "PlanCode": "P008$ ",
        "PlanName": "Plan8$ "
    },
    {
        "PlanCode": "P009$ ",
        "PlanName": "Plan9$ "
    }
]

使用如下手柄代码:

var PLAN_METHOD = {

    handlerData: function (planJSON) {

        var templateSource = $("#plan-template").html();

        template = Handlebars.compile(templateSource);

           var context = planJSON;
            plansHTML = template({planJSON:context});


        $('#plans-div').html(plansHTML);

    },
    loadPlansData: function () {

        $.get("http://localhost:41801/plan/getplans",null,this.handlerData)

    }
};

$(document).ready(function () { 

    PLAN_METHOD.loadPlansData();
});

模板html如下:

<div id="plans-div" >
</div>

<script id="plan-template" type="text/x-handlebars-template">
    <table >
        <thead>
            <tr>
                <th>Plan Code</th>
                <th>Plan Name</th>

            </tr>
        </thead>
        <tbody>
            {{#each Plans}}
            <tr>
                <td>{{this.PlanCode}}</td>
                <td>{{this.PlanName}}</td>
            </tr>
            {{/each}}
        </tbody>
    </table>
</script>

不知何故&#39;计划HTML&#39;在车把javascript代码中没有填充JSON日期行。请帮忙

1 个答案:

答案 0 :(得分:0)

您的模板正在数据的属性Plans中查找数组。但是您的数据没有Plans属性。解决方案只是在模板数据对象中使用正确的属性名称:

plansHTML = template({ Plans: context });