node express-ejs-加载中间件给页面传入数据

页面传入数据
    在ajax请求中,res.render('xx.ejs',{json数据});

    页面加载普通加载
        <%=键名%>

    加载数组或对象的循环方式
    <%for(var i=0;i<..;i++){%>
        <li><%=数组/对象[i]%>></li>
    <%}%>>  将会根据数组内容和长度创建多个li

    foreach方式

      <% 数组对象.forEach(function(ele,index){ %>
       <li><%=ele %>></li>
      <%})%>>

代码示例:
express框架:

/**
 * Created by 10853 on 2020/2/1.
 */
//引入模块
var express=require('express');

//创建服务器
var app=express();

app.set('View engine','ejs');
app.set('views','./');

//开启服务器并监听端口
app.listen(3000,function(){
    console.log('this express server is running at http://127.0.0.1:3000 ');

})

//注册app中间件use,可处理get和post请求
//app.use(function(req,res){
//    console.log('...')
//})


//注册get请求中间键
app.get('/',function(req,res){
    //服务器回应数据
    res.render('1s.ejs',{})
})

app.get('/movie',function(req,res){
    res.render('2s.ejs',{name:'jeff',age:18,hobby:['sleep','eat','love']})
})

app.post('/submit',function(req,res){
    res.send('这是一个post请求的数据');
})

2s.ejs页面:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>电影</title>
    <style type="text/css">
        .btn2{
            width: 100px;
            height: 100px;
            background: #f0f;
        }
    </style>
</head>
<body>

<button id="btn1"><%=name%>></button>
<div class="btn2"><%=age%></div>
<button id="btn3"></button>

<ul>
    <% for(var i=0;i<hobby.length;i++){%>
    <li><%=hobby[i]%></li>
    <%}%>

    <% hobby.forEach(function(ele,index){ %>
    <li><%=ele %></li>
    <% }) %>
</ul>
hhhhh


</body>
</html>
发布了387 篇原创文章 · 获赞 3 · 访问量 9164

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/104141826
今日推荐