nodejs原生(前端写死,后台改造html填充数据,未实现前后端分离)
/**
* Created by Danny on 2015/9/20 16:59.
*/
var ejs = require("ejs");
var fs = require("fs");
var http = require("http");
var server = http.createServer(function(req,res){
fs.readFile("./views/index.ejs",function(err,data){
//绑定模板
var template = data.toString();
var dictionary = {
a:6,
news : [
{"title":"陈伟我爱你","count":10},
{"title":"哈哈哈哈","count":20},
{"title":"逗你玩儿的","count":30}
]
};
// dictionary中的a news绑定到template中
var html = ejs.render(template,dictionary);
//显示
res.writeHead(200,{"Content-Type":"text/html;charset=UTF8"});
res.end(html);
});
});
server.listen(80,"127.0.0.1");
前端html(类似PHp,混编杂糅,落后技术)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>好高兴啊,今天我买了一个iphone<%= a %>s</h1>
<ul>
<%
for(var i = 0 ; i < news.length ; i++){
if(news[i].count > 15){
%>
<li><%= news[i].title %></li>
<%
}
}
%>
</ul>
</body>
</html>
express+ejs
/**
* Created by Danny on 2015/9/22 9:37.
*/
var express = require("express");
var app = express();
app.set("view engine","ejs");
app.get("/",function(req,res){
res.render("haha",{ //默认到views中查找haha.ejs
"news" : ["我是小新闻啊","我也是啊","哈哈哈哈"]
});
});
app.listen(3000);
ejs
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>哈哈哈哈</h1>
<ul>
<% for(var i = 0 ; i < news.length ; i++){ %>
<li><%= news[i] %></li>
<% } %>
</ul>
</body>
</html>