這裏再也不用ejs模版,只用Node去發送json數據,用Express靜態化public文件,content.html引用underscore模版,引用jQuery,用jQuery向服務器發送AJAX請求,把json的數據讀取到underscore的template模版內容裏。javascript
這種寫法,網頁是看不到main模塊裏的代碼,這樣是先後端更加分離,比直接用Node+ejs更分離一些。這裏新聞的news路由和json數據是後臺提供,靜態頁面向遠程服務器拉了一個json,因爲內部有模版引擎,方便了組裝。最終是用戶運行了這段程序,是你的機器在運行,運行的時候發現了幾個AJAX請求,發起了get請求,在本地進行了DOM操做。css
而用Node和ejs的話,Node充當了大管家,後端作的事更多,分離性很差。html
app.js:java
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:jquery
<!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/#templateexpress
結構:json
結果:後端