How to generate content on ejs with jquery after ajax call to express server

余生颓废 提交于 2019-11-29 02:29:42
matth

The node EJS packages comes with a client-side javascript library located in ./node_modules/ejs/ejs.js or ./node_modules/ejs/ejs.min.js. After you include this on your page, you'll want to load the template, then generate the HTML from the template. Detecting an undefined object property Javascript Sample (loading the template on page load would be a bit more ideal):

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 call in express:

app.get('/data', function (req, res) {
    res.send({ data: [
        { id: 5, name: 'Bill' },
        { id: 1, name: 'Bob' }
    ]});
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!