如何将对象数组传递到Jade模板?

4
我想从MongoDB传递一个对象数组到客户端...
这是对象。
var objeto_img=
                            {
                                name:'name of the file',
                                image:'image.jpg url',
                                title:'title of the image',
                                caption:'descripcion of the image',
                                link:"#",
                            };

在一些个人资料中,可能会有许多图像,因此会有像这样的对象数组。
[var objeto_img=
                            {
                                name:'name of the file',
                                image:'image.jpg url',
                                title:'title of the image',
                                caption:'descripcion of the image',
                                link:"#",
                            },var objeto_img=
                            {
                                name:'name of the file',
                                image:'image.jpg url',
                                title:'title of the image',
                                caption:'descripcion of the image',
                                link:"#",
                            },var objeto_img=
                            {
                                name:'name of the file',
                                image:'image.jpg url',
                                title:'title of the image',
                                caption:'descripcion of the image',
                                link:"#",
                            };]

这是服务器代码。
res.render('index/perfil_publicacion_contenido',
    {
        datos:datosRecibidos
    })

"datosRecibidos是来自mongodb的对象数组,我正在尝试在jade中放入一个变量。"
input(type='hidden',id='imagenes',value=datos.img)

但是当我尝试获取这些对象时
var fotos=$('#imagenes1').val();
            for(foto in fotos)
            {
                console.log(fotos[foto].image)
                console.log(fotos[foto].name)
                console.log(fotos[foto].caption)
                console.log(fotos[foto].title)
            }

控制台日志打印未定义。 为什么会这样???我该如何在客户端正确地从数据库获取信息?? 谢谢大家。

2
你的问题不够清晰。你想要达到什么目的? - Max
我想把对象数组放在隐藏输入框“imagenes”中。 - andrescabana86
1个回答

9
如果我理解正确,您想将对象数组序列化为输入框的value。请尝试以下代码:
- var jsonString = JSON.stringify(datos)
input(type='hidden',id='imagenes',value=jsonString)

第一行应该将对象数组转换为字符串,然后将其放入输入框的值中。
然后,当您读取该值时,您将不得不解析JSON。
var fotos = $.parseJSON($('#imagenes1').val());

我假设你使用的$是指你正在使用jQuery。
更新:说明
如果你想让一个在服务器内存中的对象可用于在浏览器中运行的Javascript,你必须将该对象“写入”页面。这个过程被正式称为序列化,用Javascript实现的方法是JSON.stringify。一旦在value中作为输入的一部分出现,它只是一个字符串。页面上的Javascript必须将该字符串转换为一个对象(或在本例中,一个对象数组)。这就是JSON.parse的作用所在。由于旧版本的浏览器没有JSON.parse,因此您应该使用像jQuery.parseJSON这样的polyfill来确保即使是旧版本的浏览器也能够将该字符串转换为Javascript对象。
顺便说一下,如果你不需要数据特定地放在hiddeninput中,但你认为那是最好的方式,让我提出另一种方法。如果你的目标是让var fotos包含来自服务器的datos的值,你可以直接在页面上的

噢,所以我必须将数组转换为字符串,然后再使用parseJSON解析成对象……谢谢,这对我有效!但如果你能解释一下为什么要这样做,我会很感激的,因为我不明白为什么要先转换成字符串,然后再用parseJSON恢复原来的过程。 - andrescabana86

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接