简体   繁体   English

如何使用ajax请求节点js处理ejs

[英]how to handle ejs with ajax request node js

Let's consider that I have test route that render my index file. 让我们考虑一下我具有渲染索引文件的测试路由。
inside index there is table that show my json file which cames form server using ejs compilation.now every thing seems good but there is problem here. 在索引内部,有一张表显示了我的json文件,该文件来自使用ejs编译的服务器。 ejs一切似乎都很好,但是这里有问题。
I call this index file with ajax GET request when the result comes ejs compilation comes with error and just my josn file has gotten form server so how can I compile ejs file and then got the result with ajax. 当结果到来时,我用ajax GET请求调用了该索引文件,而ejs编译ejs出现了错误,并且只是我的josn文件josn表单服务器获取,因此如何编译ejs文件,然后使用ajax获得结果。
So how can I compile ejs first and after that html result send to client? 那么,我该如何先编译ejs,然后将html结果发送到客户端呢?
here is my server side code : 这是我的服务器端代码:

var my_json = {
   username : "sample"
   password : "sample2"
   id : 3
}
app.route('/test').get(function(req,res){
     res.render('index',{data : myjson });
});

And here is my index.ejs file 这是我的index.ejs文件

<table id="scoreboard" class="table table-bordered tableSorter">
        <thead>
        <tr class="info">
            <th>username</th>
            <th>password</th>
            <th>id</th>
        </tr>
        </thead>
        <tbody>
           <td><%- data.username %> </td>
           <td><%- data.password %> </td>
           <td><%- data.id %> </td>
        </tbody>
</table>

And here is my js file : 这是我的js文件:

$.ajax({
      url : '/test',
      type : 'GET',
      success : function(html){
             ///I want this html comes after ejs compilation process
             $("#main").html(html);
      },
      error : function(err){
          if(err)throw err;
      }
});

First of all you should check your route work in browser and after that you should ask this question, 首先,您应该在浏览器中检查路由工作,然后再问这个问题,

just change the render line to this and every thing works fine : 只需将渲染线更改为此,一切正常:

res.render('index',{ data : my_json });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM