【问题标题】:passing locals array from Express to Javascript将本地数组从 Express 传递到 Javascript
【发布时间】:2012-02-05 07:05:31
【问题描述】:

我正在使用 Jade 和

- if (userId !== null)
  != "<script type='text/javascript'>"
  != "userDetail.userId = "+userId.toString()+";"
  - if (friends && friends.length > 0)
    != "userDetail.friends = "+friends+";"
  != "</script>"

在 Javascript 中,userDetail.js,

var userDetail = {};

userDetail.userId = null;
userDetail.friends = [];

当我运行它时,我得到 - Uncaught SyntaxError: Unexpected token ILLEGAL

我可以在 JS 中引用 userDetail.userId,但 userDetail.friends 显示为 null。 有什么线索吗?

friends 是一个对象数组 {id, name, _id}

【问题讨论】:

    标签: node.js express pug


    【解决方案1】:

    您需要使用JSON.stringify(friends),而不是您拥有的默认friends.toString()

    node
    > [{id: 42, name: "ray"}].toString()
    '[object Object]'
    > JSON.stringify([{id: 42, name: "ray"}])
    '[{"id":42,"name":"ray"}]'
    

    【讨论】:

    • 非常感谢。你的例子也很适合解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2019-10-28
    • 2017-05-07
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    相关资源
    最近更新 更多