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

handlebar not populating template correctly for JSON response

本文关键字:填充 响应 JSON handler      更新时间:2023-09-26

嗨,我正在对mvc控制器操作进行http get调用,该操作返回如下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>

不知怎的,手把javascript代码中的"plansHTML"没有填充JSON日期行。请帮助

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

plansHTML = template({ Plans: context });