【问题标题】:How to render ejs from jQuery?如何从 jQuery 渲染 ejs?
【发布时间】:2018-01-12 09:32:47
【问题描述】:

我想在从 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 %>

我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery node.js express ejs


    【解决方案1】:
    $(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 ...});
    

    【讨论】:

      【解决方案2】:

      您无法使用通过 ajax 调用收到的数据来渲染 ejs 文件。 ejs 在服务器端呈现,而 ajax 调用发生在客户端。 要解决您的问题,您需要自行在服务器端获取用户数据并将其发送到 ejs 文件。

      【讨论】:

        猜你喜欢
        • 2018-12-26
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        • 1970-01-01
        • 2012-05-08
        • 2023-03-31
        • 2019-02-13
        • 2018-12-23
        相关资源
        最近更新 更多