2014-08-28 51 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>