[英]express.js - render the full data
I am trying to render a array of object (highcharts points). 我正在尝试渲染对象数组(highcharts点)。 The data should be fine, but when I try to render, I get
[object Object]
instead of the data themselves. 数据应该很好,但是当我尝试渲染时,我得到的是
[object Object]
而不是数据本身。
JSON.stringify()
doesn t go well with HTML. JSON.stringify()
与HTML配合不佳。
util.inspect
, doesn t either, and add data. util.inspect
也不添加数据。
toString()
give me the same as the rendering. toString()
给我的效果与渲染效果相同。
I don t know what else to try, what I m trying to send is data for a highchart graphic. 我不知道还有什么可尝试的,我想发送的是highchart图形的数据。
Minimal example: 最小示例:
app.js: app.js:
var express = require('express'),
app = express();
app.listen(8080);
app.get('/', function (req, res) {
var view = 'test.ejs',
theme = [{name: '1', y: 5}, {name: '2', y: 2}];
res.render(view, {theme: theme});
console.log('ok');
});
theme_days.ejs: theme_days.ejs:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<script type="text/javascript">
<%= theme %>
</script>
</body>
</html>
Result (as if, toString()
): 结果(好像
toString()
):
[object Object],[object Object]
Result with JSON.stringify()
: JSON.stringify()
结果:
[{"name":"1","y":5},{"name":"2","y":2}]
Result with util.inspect
: util.inspect
结果:
[ { name: '1', y: 5 }, { name: '2', y: 2 } ]
EDIT: I now understand that what s happenning is that '
is escaped to html, is there a way to prevent that? 编辑:我现在知道发生了什么是
'
被转义为html,有没有办法防止这种情况?
I ended up with this: 我结束了这个:
careful, it is sub optimal: 小心,它是次优的:
app.js app.js
var express = require('express'),
app = express(),
util = require('util');
app.listen(8080);
app.get('/', function (req, res) {
var view = 'test.ejs',
theme = [{"name": "1", "y": 5}, {"name": "2", "y": 2}];//Added "
console.log(JSON.stringify(theme));
res.render(view, {theme: JSON.stringify(theme)});
console.log('ok');
});
test.ejs: test.ejs:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<script type="text/javascript">
var json = '<%= theme %>'.replace(/"/g, '"'),
theme = JSON.parse(json);
console.log(theme);
</script>
</body>
</html>
Why don't you use <%-
instead of <%=
, and pass object JSON.stringify() method. 为什么不使用
<%-
而不是<%=
,并传递对象JSON.stringify()方法。
The first one will render object in HTML, the second one will render variables (as they are, eval) 第一个将呈现HTML中的对象,第二个将呈现变量(按原样评估)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.