2
我想从帕格传递JSON对象到客户端JavaScript。代码的结构如下。我渲染一个JSON对象,并将它从我的Node-Express后端传递给Pug。下面的代码:如何将帕格JSON对象传递到客户端JavaScript
server.js
:
app.get('/myrooms', function(req, res) {
Room.find()
.where('_id')
.in(user.rooms)
.exec(function (err, records) {
res.render('rooms/index', {myrooms : records})
})
})
在此之后的对象是我的哈巴狗文件中。现在我想将它传递给客户端脚本。我在我的index.pug
文件中做了这样的事情。
index.pug
:
script(src='/js/play.js').
trooms = "#{myrooms}"
play.js
:
console.log(trooms)
它给了我 '没有定义troom
' 的错误。我不知道如何通过这个对象。根据一些旧帖子,这是在玉器工作。但是,我使用的是帕格版本2.0.0-rc.2
。
你必须走出'trooms = “#{} myrooms”'你的源脚本之前。 – lxe
另外,需要调用'JSON.parse('#{myrooms}')'将JSON转换为对象。 – alexmac
我尝试过'JSON.parse('#{myrooms}')',但它没有工作。 – Shadid