【问题标题】:How to pass data from ajax success and render in handlebars template?如何从 ajax 成功传递数据并在车把模板中呈现?
【发布时间】:2020-05-20 19:48:23
【问题描述】:

我在 .hbs 文件中有这个

                    <div class="col-12 col-md-3 order-md-1">
                        <div id="notes">
                            {{#each notes}}
                                {{>note}}
                            {{/each}}
                        </div>
                    </div>

这是我的 jquery:

$.ajax({
    url: '/search/notes',
    method: 'GET',
    data: {
        search_string: 'server'
    },
    success: function(response) {
        var source = $('#notes').html()
        var template = Handlebars.compile(source)
        var context = {
            notes : response.notes,
        }
        var el_html = template(context);
        console.log(el_html)
        $('#notes').html(el_html)
    }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>

我无法在id="notes" 上获得notes。它导致空白div。有什么帮助吗?

【问题讨论】:

    标签: jquery node.js ajax handlebars.js


    【解决方案1】:

    您的 Ajax 响应可能存在问题。下面的示例在没有 Ajax 的情况下工作。

    setTimeout(function() {
    var source = $('#notes').html()
    var template = Handlebars.compile(source)
    var context = {
        notes : ["test", "test2"],
    }
    var el_html = template(context);
    console.log(el_html);
    $('#notes').html(el_html);
    }, 2000);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
    <div class="col-12 col-md-3 order-md-1">
                            <div id="notes">
                                {{#each notes}}
                                    {{this}}
                                {{/each}}
                            </div>
                        </div>

    【讨论】:

    • 我通过 ajax 得到了正确的响应。调用部分 hbs 文件 {{>note}} 似乎有问题
    • 实际上,我正在尝试通过 ajax 覆盖 id="note" div 上已经存在的内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2016-06-19
    • 2021-09-02
    相关资源
    最近更新 更多