节点/快速 - 响应中的多个渲染视图

时间:2015-07-15 20:34:25

标签: ajax node.js express routes

我正在执行一个AJAX调用,并且我想返回一个JSON响应,其中包含几个渲染的部分视图,我可以用它来交换我页面的不同部分。所以,例如:

<div id="marketAccessTableView" class="maTable">

    <div class="maCol L1">
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN1</label></div>
    </div>
    <div class="maCol L2">
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN2</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN2</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN2</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN2</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN2</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN2</label></div>
    </div>
    <div class="maCol L7">
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
        <div class="maRow"><label><input type="checkbox" name="vehicle" value="Bike"> SGN3</label></div>
    </div>
</div>

我的应用程序基于Node / Express构建,Express-Handlebars作为我的视图引擎。我的想法是在我的路线中做这样的事情:

{
    "searchResults": "<div>Some HTML string</div>",
    "paginationBar": "<div>Another HTML string</div>"
}

我该怎么做

1 个答案:

答案 0 :(得分:2)

如果定义了res.app.render,你的代码看起来很好,但你需要嵌套它,因为渲染代码可能是异步的:

  var renderedViews = {};

  res.app.render('partials/search/products', {layout: 'ajax'}, function (err, html) {
    renderedViews.searchResults = html;

    res.app.render('partials/search/pagination', {layout: 'ajax'}, function (err, html) {
      renderedViews.pagination = html;

      res.json(renderedViews);
    });
  });