一、express应用中ajax结合模板引擎ejs.js渲染页面
在views新建一个渲染模板命名 Template.ejs
Template.ejs 示例:
<% if(coursesList.length!=0){ %>
<% coursesList.forEach(function(c){ %>
<a href=ttp://hc.6636fu.com/yuehao_pc/index.html?shopId= <%= c.shopId %> target="_blank">
<div class="catalogcourse detailhover" data-id=<%= c.shopId %> style="height: 217px;">
<img src=http://hc.6636fu.com/<%= c.curriculumImg %> alt="">
<p class="catalogname"><%= c.curriculumName %></p>
<div class="jpcoursebx flex">
<img src="/images/location.png" alt="">
<p><%= c.shopAddress %></p>
</div>
<div class="jq-price-box">
<% if(c.isOpenPrice == "1"){ %>
<p class="jq-now">
<span>¥</span><%= c.currPrice %></p>
<p class="jq-origin">
<span>¥</span>4890</p>
<% } else { %>
<div class="jq-zixun" data-shopid="${c.shopId}">电话咨询</div>
<% } %>
</div>
</div>
</a>
<% }) %>
<% } else if(coursesList.length==0){ %>
<p style="font-size: 18px;color: #666;width: 100%;text-align: center;padding: 200px 0;">暂无更多数据~</p>
<% } %>
<script>
pages = <%- JSON.stringify(page) %>;
try {
paging();
} catch (error) {
// console.log(error);
}
</script>
index.ejs使用
<!--课程列表-->
<div class="catalogcoursebox flex">
<% include course.ejs %>
</div>
routes 的 index.js 首次渲染
res.render('index', {
title: '会计课程',
coursesList,
page,
});
index.ejs:发起ajax异步请求,其他课程分类的数据
function getList() {
$('.catalogcoursebox').children().remove();
$.post("/index/coursecatalog", _param, function (data) {
$('.catalogcoursebox').append(data); //往盒子添加数据,这里 的data数据为字符串的标签,不用再自己组了,啊呵呵呵
if (typeof (pages) == "string") {
pages = JSON.parse(pages);
}
$('.justify').text("共" + pages.totalCount + "条记录");
if(pages.totalCount==0){
$('.pageno').css('display','none');
}else{
$('.pageno').css('display','flex');
}
})
}
routes 的 index.js 响应请求,
// 点击请求课程
router.post('/coursecatalog', function (req, res, next) {
let addrrss_op = {
url: 'http://hc.6*****',
method: "post",
json: true,
headers: {
"content-type": "application/json",
},
body: req.body
};
console.log(req.body);//接收ajax的参数
async function implement() {
let rest = await reqPme(addrrss_op); //课程列表
console.log('----------------');
console.log(rest.data);
page=rest.page;
res.render('Template', { coursesList: rest.data,page });
}
implement().catch(error => console.log(error.message));
})
然后就完成了。。。。。。。。。。
做法是用ajax请求node然后用返回的(字符串的标签)数据进行append渲染
还不清楚这样的写法会造成啥弊端,还望各位大佬指出~