如何从jQuery渲染ejs?

我想从API获取数据后呈现文件。

$(document).ready(function() { $(document).delegate( "#editUser", "click", function() { var userId = $(this).data('id'); $.post("/userProfile",{"userId":userId},function(data, status){ console.log(data); //gets data here //how to render ejs file here with the above data? }); }); 

ejs文件: (sample.ejs)

 <% include header.html %> <strong>Sample ejs</strong> <ul> <li><%= data.name %> says: <%= data.message %></li> </ul> <% include footer.html %> 

我怎么解决这个问题?

 $(document).ready(function() { $(document).delegate( "#editUser", "click", function() { var userId = $(this).data('id'); $.post("/userProfile",{"userId":userId},function(html, status){ $("#some-container").append(html); }); }); 

上面的代码假设你从服务器端渲染ejs模板,如下所示:

 res.render('sample', {param1: param1 ...}); 

您不能使用Ajax调用接收到的数据来呈现ejs文件。 ejs在服务器端渲染,在客户端发生ajax调用。 为了解决你的问题,你需要在服务器端获取用户数据,并将其发送到ejs文件。