我正在尝试使用来自Node JS的数据来使用Amcharts。我试图将一个json作为Node服务器flie响应的一部分传递给客户端,我可以使用feed amcharts创建一个饼图。代码如下 -
app.js
var express = require('express');
var path = require('path');
var app = express();
var port = process.env.PORT || 5000;
var delivCount = require('./serv_delivered.js');
var serv_ontime = require('./serv_ontime.js');
var delayedCount = require('./serv_delayed.js');
var crtidelayedCount = require('./serv_crit_delayed.js');
var chartData = [{
"country": "Czech",
"litres": 301.9
}, {
"country": "Ireland",
"litres": 201.1
}, {
"country": "Germany",
"litres": 165.8
}, {
"country": "Pak",
"litres": 139.9
}, {
"country": "Austria",
"litres": 128.3
}, {
"country": "UK",
"litres": 99
}] ;
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/src/views');
var bookRouter= express.Router();
app.set('view engine','ejs');
app.get('/',function(req,res){
delivCount(function(error, res_deliv){
serv_ontime(function(error, res_ontime){
delayedCount(function(error, res_delayed){
crtidelayedCount(function(error, res_cdelayed){
res.render('index', {title: "Hellow From Render",
res: [res_deliv,res_ontime,res_delayed,res_cdelayed,chartData]
});
});
});
});
});
});
app.listen(port,function(err){
console.log('running server on port'+ port);
});
amchart5.js
var chart = AmCharts.makeChart("pie1", {
"type": "pie",
"theme": "light",
"dataProvider": [{
"country": "Czech",
"litres": 301.9
}, {
"country": "Ireland",
"litres": 201.1
}, {
"country": "Germany",
"litres": 165.8
}, {
"country": "Pak",
"litres": 139.9
}, {
"country": "Austria",
"litres": 128.3
}, {
"country": "UK",
"litres": 99
}],
"valueField": "litres",
"titleField": "country",
"balloon": {
"fixedPosition": true
},
"export": {
"enabled": true
}
});
有人可以帮我使用我从app.js发送的 chartData 来创建饼图吗?
添加验证正确数据的屏幕截图 -
答案 0 :(得分:1)
如果您的服务器返回正确的值,并且您正在使用外部js
文件,则可以执行以下操作。
function createChart(chartData){
var chart = AmCharts.makeChart("pie1", {
"type": "pie",
"theme": "light",
"dataProvider": chartData,
"valueField": "litres",
"titleField": "country",
"balloon": {
"fixedPosition": true
},
"export": {
"enabled": true
}
});
}
然后从ejs文件中调用该函数
<script>
createChart(<%- res[4] %>);
</script>
当您将res
声明为数组且图表数据位于索引4时,这应该可行。
p.s:也许您需要在数组中使用JSON.stringify
并注意脚本的加载顺序。