2014-08-28 81 views
0

我正在尝试呈现对象数组(高热点点)。数据应该没问题,但是当我尝试渲染时,我得到[object Object]而不是数据本身。express.js - 呈现完整数据

JSON.stringify()不适合HTML。

util.inspect,也没有,并添加数据。

toString()给我跟渲染一样。

我不知道还有什么可以尝试的,我试图发送的是一张高图表的数据。

最少例如:

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()

[{&quot;name&quot;:&quot;1&quot;,&quot;y&quot;:5},{&quot;name&quot;:&quot;2&quot;,&quot;y&quot;:2}] 

结果与util.inspect

[ { name: &#39;1&#39;, y: 5 }, { name: &#39;2&#39;, y: 2 } ] 

编辑: 我现在明白了,有何happenning是'被转义为HTML,是有办法阻止?

+1

的eacaping happends在模板水平看到这对于溶液http://stackoverflow.com/questions/ 8547131/how-to-include-html-code-in-a-view – Max 2014-08-28 09:58:36

+1

@Max:Urg,和JSON.stringify不断解决问题... – DrakaSAN 2014-08-28 10:15:06

回答

1

为什么不您使用​​3210而不是<%=,并传递对象JSON.stringify()方法。

第一个将在HTML渲染对象,第二个将呈现变量(因为它们是,EVAL)

0

我结束了与此:

小心,这是次优:

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(/&quot;/g, '"'), 
       theme = JSON.parse(json); 
      console.log(theme); 
     </script> 
    </body> 
</html>