使用nodejs编写后台从数据库中读取数据,再渲染到前端html文件用Echart画图
1.nodejs后台
var express = require('express');
var swig = require('swig');
var app = express();
var mysql=require('mysql');
//设置swig页面不缓存
// swig.setDefaults({cache: false});
// app.set('view cache', false);
app.set('views','/home/jun/study/echart/views');
app.set('view engine','html');
app.engine('html', swig.renderFile);
app.listen(4000);
console.log('server is started at http://localhost:4000');
//index page
app.get('/',function(req, res){
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test'
});
connection.connect();
connection.query('select * from db_1', function (err, data) {
if (err) throw err;
var name = [];
var score = [];
for (var i = 0; i < data.length; i++) {
name[i] = (data[i].name).toString();
score[i] = data[i].score;
}
res.render('index',{
title:'首页 ',
content: 'Echart Test',
name:name,
score:score
});
});
});
2.前端html模板页面
<!DOCTYPE html>
<html style="height: 100%">
<head>
<meta charset="utf-8">
<title>{{ title }}</title>
</head>
<body style="height: 100%; margin: 0">
<h1>{{content}}</h1>
<div id="container" style="height: 100%"></div>
<script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/echarts.min.js"></script>
<script type="text/javascript">
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
option = null;
var option = {
xAxis: {
type: 'category',
// data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
// data:[{{score}}]
data: '{{name}}'.split(',')
},
yAxis: {
type: 'value'
},
series: [{
// data: [1,2,3,4,5,6,7],
data:'{{score}}'.split(','),
type: 'line'
}]
};
if (option && typeof option === "object") {
myChart.setOption(option, true);
}
</script>
</body>
</html>
展示效果图:
找了好久都没找到关于nodejs传递参数到前端html渲染的,一般都是用ejs渲染引擎。
搞了两天,终于写出来了,希望对你也有所帮助。(相关知识点后续再完善)