簡體   English   中英

如何使用ajax請求節點js處理ejs

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

讓我們考慮一下我具有渲染索引文件的測試路由。
在索引內部,有一張表顯示了我的json文件,該文件來自使用ejs編譯的服務器。 ejs一切似乎都很好,但是這里有問題。
當結果到來時,我用ajax GET請求調用了該索引文件,而ejs編譯ejs出現了錯誤,並且只是我的josn文件josn表單服務器獲取,因此如何編譯ejs文件,然后使用ajax獲得結果。
那么,我該如何先編譯ejs,然后將html結果發送到客戶端呢?
這是我的服務器端代碼:

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

這是我的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>

這是我的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;
      }
});

首先,您應該在瀏覽器中檢查路由工作,然后再問這個問題,

只需將渲染線更改為此,一切正常:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM