【问题标题】:json.stringify returns [object object]json.stringify 返回 [object object]
【发布时间】:2015-01-24 09:51:31
【问题描述】:

我有 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 文件并从中获取时间列。

//我知道用jade。我们写得像

//对于索引中的每个a

// a.time -> 给你每次输入

我正在尝试使用 ejs 来获得相同的效果。在 index.js 文件中

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

但这只是输出

我的 UI 上的[object Object]

谁能解释一下如何在 ejs 中做到这一点? 我想获取数组或其他东西的时间条目,但我不明白如何继续。

【问题讨论】:

    标签: javascript json node.js cassandra ejs


    【解决方案1】:

    1

    如果你想将变量从玉文件传递到 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

    如果你只想在翡翠文件中获取价值,你可以这样做

    index.jade

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

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

    【讨论】:

      【解决方案2】:

      你已经将 index 名称中的数据对象传递给了 ejs 视图

      var myVar = <%- JSON.stringify(index) %>; 
      
      alert(myVar[0].uuid)
      // document.getElementById("pil").innerHTML= myVar;
      

      【讨论】:

      • alert('
      • 警报不会在屏幕上弹出。但是我试过说 document.getElementById("pil").innerHTML= myVar[0];现在它在屏幕上显示“未定义”而不是 [object Object]
      猜你喜欢
      • 2015-11-11
      • 2017-12-30
      • 2013-05-05
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2015-07-16
      相关资源
      最近更新 更多