【问题标题】:express.js - render the full dataexpress.js - 渲染完整数据
【发布时间】:2014-08-28 09:06:32
【问题描述】:

我正在尝试渲染一个对象数组(highcharts 点)。数据应该没问题,但是当我尝试渲染时,我得到[object Object] 而不是数据本身。

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 } ]

编辑: 我现在明白发生了什么是' 被转义为 html,有没有办法防止这种情况发生?

【问题讨论】:

标签: javascript html node.js express


【解决方案1】:

你为什么不使用&lt;%-而不是&lt;%=,并传递对象JSON.stringify()方法。

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

【讨论】:

    【解决方案2】:

    我最终得到了这个:

    小心,这是次优的:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多