How to render ejs from jQuery?

自闭症网瘾萝莉.ら 提交于 2019-12-10 23:35:37

问题


I want to render a file after getting the data from the API.

code

$(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 file: (sample.ejs)

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

How can I solve this problem?


回答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);
    });
});

The above code assumes you're rendering ejs template from server side like so:

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



回答2:


You can't render the ejs file with the data what you receive with ajax call. ejs renders at server side, where as the ajax call happens on the client side. To solve your issue you need to get the user data at server side it self and send it to ejs file.



来源:https://stackoverflow.com/questions/45506894/how-to-render-ejs-from-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!