json+underscore+Node 小例子
这里不再用ejs模版,只用Node去发送json数据,用Express静态化public文件,content.html引用underscore模版,引用jQuery,用jQuery向服务器发送AJAX请求,把json的数据读取到underscore的template模版内容里。
这种写法,网页是看不到main模块里的代码,这样是前后端更加分离,比直接用Node+ejs更分离一些。这里新闻的news路由和json数据是后台提供,静态页面向远程服务器拉了一个json,由于内部有模版引擎,方便了组装。最终是用户运行了这段程序,是你的机器在运行,运行的时候发现了几个AJAX请求,发起了get请求,在本地进行了DOM操作。
而用Node和ejs的话,Node充当了大管家,后端做的事更多,分离性不好。
app.js:
var express = require("express");
var app = express();
app.use(express.static("./public"));
var shujuku = [
{
"biaoti":"我是1号新闻啊!我很开心啊",
"shijian":"2017年11月14日09:21:03",
"zuozhe":"考拉",
"neirong":"<p>内容啊内容啊内容啊内容啊</p>"
},
{
"biaoti":"我是2号新闻啊!我很开心啊",
"shijian":"2017年11月14日09:21:03",
"zuozhe":"Bob",
"neirong":"内容啊内容啊内容啊内容啊"
},
{
"biaoti":"我是3号新闻啊!我很开心啊",
"shijian":"2017年11月14日09:21:03",
"zuozhe":"Jack",
"neirong":"内容啊内容啊内容啊内容啊"
},
{
"biaoti":"我是4号新闻啊!我很开心啊",
"shijian":"2017年11月14日09:21:03",
"zuozhe":"hehe",
"neirong":"内容啊内容啊内容啊内容啊"
}
];
app.get("/news",function (req,res) {
//相当于send的时候发的是json数据
res.json(shujuku);
});
app.listen(3000);
content.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.header{
width:980px;
height:100px;
margin:0 auto;
background-color: #ccc;
margin-bottom: 20px;
}
.content {
width:980px;
margin:0 auto;
}
.main {
float: left;
width:599px;
margin-right: 20px;
border-right:1px solid red;
}
.aside {
float: left;
width: 360px;
height: 400px;
background-color: #ccc;
}
h1 {
text-align: center;
}
.grid {
border-bottom: 1px solid #333;
box-shadow: 1px 1px 1px #333;
margin-bottom: 10px;
border-radius: 10px
padding: 10px;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="header"></div>
<div class="content">
<div class="main">
</div>
<div class="aside"></div>
</div>
<script type="text/template" id = "moban">
<div class="grid">
<h3><%= biaoti %></h3>
<p>发布时间:<%= shijian %> 作者:<%= zuozhe %></p>
<p><%= neirong %></p>
<p><a href="">详细</a></p>
</div>
</script>
<script type = "text/javascript" src = "jquery-1.11.3.min.js"></script>
<script type="text/javascript" src = "underscore.js"></script>
<script type="text/javascript">
//得到模版内容
var mobanstring = $("#moban").html();
var compiled = _.template(mobanstring);
//发出AJAX请求
$.get("/news",function (data,status) {
for(var i = 0; i < data.length; i++) {
var compiledString = compiled(data[i]);
$(".main").append($(compiledString));
}
});
</script>
</body>
</html>
template用法:http://www.bootcss.com/p/underscore/#template
结构:
结果:
在线预览:https://jsfiddle.net/papersnake/kf02h9x2/