如何在ajax调用express服务器之后使用jquery在ejs上生成内容
我想在我的网站上实现一个搜索function,所以我要做的是用一个jquery ajax调用文本到快速服务器,它搜索mongodb并给出一个匹配的用户的对象数组。 现在我成功地收到了这个对象,但由于ejs上没有部分内容,我如何只刷新为每个用户生成html的结果列表?
节点EJS包附带一个位于./node_modules/ejs/ejs.js
或./node_modules/ejs/ejs.min.js
的客户端javascript库。 在页面上包含此内容后,您将需要加载模板,然后从模板生成HTML。 检测未定义的对象属性 Javascript Sample(在页面加载时加载模板会更加理想):
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:
ID Name <% data.forEach(function (d) { %> <%- d.id %> <%- d.name %> <% }); %>
Ajax调用快递:
app.get('/data', function (req, res) { res.send({ data: [ { id: 5, name: 'Bill' }, { id: 1, name: 'Bob' } ]}); });