node_ejs 模板引擎

node_ejs 模板引擎

  1. 中文文档https://ejs.bootcss.com/#install

  2. 案列1:通过ajax方式请求后端数据

    后端文件:01.js
    const express = require("express");
    
    let app = express();
    app.listen(4567);
    
    app.get("/",(req,res)=>{
        res.sendFile(require("path").join(__dirname,"./test.html"));//通过浏览器发送一个get请求给后端,返回一个html页面
    });
    app.post("/",(req,res)=>{
        /*假设这里是从数据库拿到的数据*/
        let data = [
            {name: "皮卡",age: "18",sex: "男"},
            {name: "小希",age: "34",sex: "男"},
            {name: "小红",age: "20",sex: "女"},
            {name: "小远",age: "32",sex: "男"},
            {name: "阿伟",age: "21",sex: "男"}
        ];
        res.send(data);//将数据返回给前端
    });
    
    html前端页面:test.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            table{border-collapse: collapse;}
        </style>
    </head>
    <body>
    <table border="1">
        <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>  
    </table>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $.ajax({
            type : "POST",
            url : "/",
            success(msg){
                let $table = $("table");
                let html = "";
                msg.forEach(item=>{
                    html += `<tr>
                        <td>${item.name}</td>
                        <td>${item.age}</td>
                        <td>${item.sex}</td>
                        </tr>`;
                });
                $table.append(html);
            }
        });
    </script>
    </body>
    </html>
    
上一篇:Nodejs ejs模板引擎


下一篇:Express 框架中 ejs 的安装使用