json.stringify返回[object object]

时间:2014-11-26 06:45:04

标签: javascript json node.js cassandra ejs

我有node-express-ejs和cassandra数据库。 我正在读取index.js文件中来自cassandra的表。

router.get('/index', function(req, res) {
    client.connect(function(err) {});
    client.execute('SELECT * FROM data.test;', function(err, result) {
        var user = result.rows[2];
        console.log("here is the user", result);
        res.render('index', {
            "index": result
        });
    });
});

我有以下结果的日志:

我正在尝试将此结果传递给.ejs文件,并从中获取时间列。

//我知道使用玉。我们写得像

//索引中的每个a

// a.time - >每次进入时都会给你

我正在努力使用ejs。在index.js文件中

 var myVar = <%- JSON.stringify(index) %>; 
 document.getElementById("pil").innerHTML= myVar;

但这只是输出

我的用户界面

[对象]

有谁能解释如何在ejs中做到这一点? 我想把时间条目输入数组或其他东西,但我不明白如何继续相同。

enter image description here

2 个答案:

答案 0 :(得分:1)

您已将索引名称中的数据对象传递给ejs view

var myVar = <%- JSON.stringify(index) %>; 

alert(myVar[0].uuid)
// document.getElementById("pil").innerHTML= myVar;

答案 1 :(得分:1)

1

如果你想从jade文件传递变量到index.js文件,你应该做这样的事情

<强> index.jade

script.
  var myVar = !{JSON.stringify(index)}  
script(src='/javascripts/index.js')

div(id='pil')

在我们的例子中,myVar将是对象,因此index.js应该看起来像这样

<强> index.js

window.onload = function () {
  document.getElementById('pil').innerHTML = JSON.stringify(myVar);

  // show time for first item in array 
  // document.getElementById('pil').innerHTML = myVar.rows[0].time;
};

我们调用stringify,因为正如我之前所说的myVar是对象所以我们需要将它转换为字符串。

2

如果你想在jade文件中获取值,你可以这样做

<强> index.jade

div(id='pil')
  =index.rows[0].time

index.rows是包含对象的数组,因此您需要为数组指定索引(在我们的例子中,我们指定了index.rows [0])并获取您想要的字段,例如.time。

相关问题