5

我想在我的网站上实现一个搜索功能,所以我所做的就是对快速服务器进行带有文本的 jquery ajax 调用,该服务器搜索 mongodb 并提供匹配的用户的对象数组。现在我成功地收到了这个对象,但是由于 ejs 上没有部分内容,我如何才能只刷新为每个用户生成 html 的结果列表?

4

1 回答 1

9

节点 EJS 包附带一个位于./node_modules/ejs/ejs.js或中的客户端 JavaScript 库./node_modules/ejs/ejs.min.js。在页面中包含此内容后,您需要加载模板,然后从模板生成 HTML。 检测未定义的对象属性 Javascript 示例(在页面加载时加载模板会更理想一些):

function getData() {
    // Grab the template
    $.get('/results.ejs', function (template) {
        // Compile the EJS template.
        var func = ejs.compile(template);

        // Grab the data
        $.get('/data', function (data) {
           // Generate the html from the given data.
           var html = func(data);
           $('#divResults').html(html);
        });
    });
}

EJS:

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
    </tr>   
    <% data.forEach(function (d) { %>
    <tr>
        <td><%- d.id %></td>
        <td><%- d.name %></td>
    </tr>
    <% }); %>
</table>

Ajax 快速调用:

app.get('/data', function (req, res) {
    res.send({ data: [
        { id: 5, name: 'Bill' },
        { id: 1, name: 'Bob' }
    ]});
});
于 2013-09-24T20:27:53.160 回答