[英]express.js - render the full data
我正在嘗試渲染對象數組(highcharts點)。 數據應該很好,但是當我嘗試渲染時,我得到的是[object Object]
而不是數據本身。
JSON.stringify()
與HTML配合不佳。
util.inspect
也不添加數據。
toString()
給我的效果與渲染效果相同。
我不知道還有什么可嘗試的,我想發送的是highchart圖形的數據。
最小示例:
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:
<!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>
結果(好像toString()
):
[object Object],[object Object]
JSON.stringify()
結果:
[{"name":"1","y":5},{"name":"2","y":2}]
util.inspect
結果:
[ { name: '1', y: 5 }, { name: '2', y: 2 } ]
編輯:我現在知道發生了什么是'
被轉義為html,有沒有辦法防止這種情況?
我結束了這個:
小心,它是次優的:
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:
<!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>
為什么不使用<%-
而不是<%=
,並傳遞對象JSON.stringify()方法。
第一個將呈現HTML中的對象,第二個將呈現變量(按原樣評估)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.